now that libsystem no longer uses SmallVector, we can move
[oota-llvm.git] / lib / VMCore / Function.cpp
1 //===-- Function.cpp - Implement the Global object classes ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Function class for the VMCore library.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Module.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/IntrinsicInst.h"
17 #include "llvm/LLVMContext.h"
18 #include "llvm/CodeGen/ValueTypes.h"
19 #include "llvm/Support/LeakDetector.h"
20 #include "llvm/Support/ManagedStatic.h"
21 #include "llvm/Support/StringPool.h"
22 #include "llvm/System/RWMutex.h"
23 #include "llvm/System/Threading.h"
24 #include "SymbolTableListTraitsImpl.h"
25 #include "llvm/ADT/DenseMap.h"
26 #include "llvm/ADT/StringExtras.h"
27 using namespace llvm;
28
29
30 // Explicit instantiations of SymbolTableListTraits since some of the methods
31 // are not in the public header file...
32 template class SymbolTableListTraits<Argument, Function>;
33 template class SymbolTableListTraits<BasicBlock, Function>;
34
35 //===----------------------------------------------------------------------===//
36 // Argument Implementation
37 //===----------------------------------------------------------------------===//
38
39 Argument::Argument(const Type *Ty, const Twine &Name, Function *Par)
40   : Value(Ty, Value::ArgumentVal) {
41   Parent = 0;
42
43   // Make sure that we get added to a function
44   LeakDetector::addGarbageObject(this);
45
46   if (Par)
47     Par->getArgumentList().push_back(this);
48   setName(Name);
49 }
50
51 void Argument::setParent(Function *parent) {
52   if (getParent())
53     LeakDetector::addGarbageObject(this);
54   Parent = parent;
55   if (getParent())
56     LeakDetector::removeGarbageObject(this);
57 }
58
59 /// getArgNo - Return the index of this formal argument in its containing
60 /// function.  For example in "void foo(int a, float b)" a is 0 and b is 1. 
61 unsigned Argument::getArgNo() const {
62   const Function *F = getParent();
63   assert(F && "Argument is not in a function");
64   
65   Function::const_arg_iterator AI = F->arg_begin();
66   unsigned ArgIdx = 0;
67   for (; &*AI != this; ++AI)
68     ++ArgIdx;
69
70   return ArgIdx;
71 }
72
73 /// hasByValAttr - Return true if this argument has the byval attribute on it
74 /// in its containing function.
75 bool Argument::hasByValAttr() const {
76   if (!isa<PointerType>(getType())) return false;
77   return getParent()->paramHasAttr(getArgNo()+1, Attribute::ByVal);
78 }
79
80 /// hasNestAttr - Return true if this argument has the nest attribute on
81 /// it in its containing function.
82 bool Argument::hasNestAttr() const {
83   if (!isa<PointerType>(getType())) return false;
84   return getParent()->paramHasAttr(getArgNo()+1, Attribute::Nest);
85 }
86
87 /// hasNoAliasAttr - Return true if this argument has the noalias attribute on
88 /// it in its containing function.
89 bool Argument::hasNoAliasAttr() const {
90   if (!isa<PointerType>(getType())) return false;
91   return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoAlias);
92 }
93
94 /// hasNoCaptureAttr - Return true if this argument has the nocapture attribute
95 /// on it in its containing function.
96 bool Argument::hasNoCaptureAttr() const {
97   if (!isa<PointerType>(getType())) return false;
98   return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoCapture);
99 }
100
101 /// hasSRetAttr - Return true if this argument has the sret attribute on
102 /// it in its containing function.
103 bool Argument::hasStructRetAttr() const {
104   if (!isa<PointerType>(getType())) return false;
105   if (this != getParent()->arg_begin())
106     return false; // StructRet param must be first param
107   return getParent()->paramHasAttr(1, Attribute::StructRet);
108 }
109
110 /// addAttr - Add a Attribute to an argument
111 void Argument::addAttr(Attributes attr) {
112   getParent()->addAttribute(getArgNo() + 1, attr);
113 }
114
115 /// removeAttr - Remove a Attribute from an argument
116 void Argument::removeAttr(Attributes attr) {
117   getParent()->removeAttribute(getArgNo() + 1, attr);
118 }
119
120
121 //===----------------------------------------------------------------------===//
122 // Helper Methods in Function
123 //===----------------------------------------------------------------------===//
124
125 LLVMContext &Function::getContext() const {
126   return getType()->getContext();
127 }
128
129 const FunctionType *Function::getFunctionType() const {
130   return cast<FunctionType>(getType()->getElementType());
131 }
132
133 bool Function::isVarArg() const {
134   return getFunctionType()->isVarArg();
135 }
136
137 const Type *Function::getReturnType() const {
138   return getFunctionType()->getReturnType();
139 }
140
141 void Function::removeFromParent() {
142   getParent()->getFunctionList().remove(this);
143 }
144
145 void Function::eraseFromParent() {
146   getParent()->getFunctionList().erase(this);
147 }
148
149 //===----------------------------------------------------------------------===//
150 // Function Implementation
151 //===----------------------------------------------------------------------===//
152
153 Function::Function(const FunctionType *Ty, LinkageTypes Linkage,
154                    const Twine &name, Module *ParentModule)
155   : GlobalValue(PointerType::getUnqual(Ty), 
156                 Value::FunctionVal, 0, 0, Linkage, name) {
157   assert(FunctionType::isValidReturnType(getReturnType()) &&
158          !isa<OpaqueType>(getReturnType()) && "invalid return type");
159   SymTab = new ValueSymbolTable();
160
161   // If the function has arguments, mark them as lazily built.
162   if (Ty->getNumParams())
163     SubclassData = 1;   // Set the "has lazy arguments" bit.
164   
165   // Make sure that we get added to a function
166   LeakDetector::addGarbageObject(this);
167
168   if (ParentModule)
169     ParentModule->getFunctionList().push_back(this);
170
171   // Ensure intrinsics have the right parameter attributes.
172   if (unsigned IID = getIntrinsicID())
173     setAttributes(Intrinsic::getAttributes(Intrinsic::ID(IID)));
174
175 }
176
177 Function::~Function() {
178   dropAllReferences();    // After this it is safe to delete instructions.
179
180   // Delete all of the method arguments and unlink from symbol table...
181   ArgumentList.clear();
182   delete SymTab;
183
184   // Remove the function from the on-the-side GC table.
185   clearGC();
186 }
187
188 void Function::BuildLazyArguments() const {
189   // Create the arguments vector, all arguments start out unnamed.
190   const FunctionType *FT = getFunctionType();
191   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
192     assert(FT->getParamType(i) != Type::getVoidTy(FT->getContext()) &&
193            "Cannot have void typed arguments!");
194     ArgumentList.push_back(new Argument(FT->getParamType(i)));
195   }
196   
197   // Clear the lazy arguments bit.
198   const_cast<Function*>(this)->SubclassData &= ~1;
199 }
200
201 size_t Function::arg_size() const {
202   return getFunctionType()->getNumParams();
203 }
204 bool Function::arg_empty() const {
205   return getFunctionType()->getNumParams() == 0;
206 }
207
208 void Function::setParent(Module *parent) {
209   if (getParent())
210     LeakDetector::addGarbageObject(this);
211   Parent = parent;
212   if (getParent())
213     LeakDetector::removeGarbageObject(this);
214 }
215
216 // dropAllReferences() - This function causes all the subinstructions to "let
217 // go" of all references that they are maintaining.  This allows one to
218 // 'delete' a whole class at a time, even though there may be circular
219 // references... first all references are dropped, and all use counts go to
220 // zero.  Then everything is deleted for real.  Note that no operations are
221 // valid on an object that has "dropped all references", except operator
222 // delete.
223 //
224 void Function::dropAllReferences() {
225   for (iterator I = begin(), E = end(); I != E; ++I)
226     I->dropAllReferences();
227   
228   // Delete all basic blocks.
229   while (!BasicBlocks.empty()) {
230     // If there is still a reference to the block, it must be a 'blockaddress'
231     // constant pointing to it.  Just replace the BlockAddress with undef.
232     BasicBlock *BB = BasicBlocks.begin();
233     if (!BB->use_empty()) {
234       BlockAddress *BA = cast<BlockAddress>(BB->use_back());
235       BA->replaceAllUsesWith(UndefValue::get(BA->getType()));
236       BA->destroyConstant();
237     }
238     
239     BB->eraseFromParent();
240   }
241 }
242
243 void Function::addAttribute(unsigned i, Attributes attr) {
244   AttrListPtr PAL = getAttributes();
245   PAL = PAL.addAttr(i, attr);
246   setAttributes(PAL);
247 }
248
249 void Function::removeAttribute(unsigned i, Attributes attr) {
250   AttrListPtr PAL = getAttributes();
251   PAL = PAL.removeAttr(i, attr);
252   setAttributes(PAL);
253 }
254
255 // Maintain the GC name for each function in an on-the-side table. This saves
256 // allocating an additional word in Function for programs which do not use GC
257 // (i.e., most programs) at the cost of increased overhead for clients which do
258 // use GC.
259 static DenseMap<const Function*,PooledStringPtr> *GCNames;
260 static StringPool *GCNamePool;
261 static ManagedStatic<sys::SmartRWMutex<true> > GCLock;
262
263 bool Function::hasGC() const {
264   sys::SmartScopedReader<true> Reader(*GCLock);
265   return GCNames && GCNames->count(this);
266 }
267
268 const char *Function::getGC() const {
269   assert(hasGC() && "Function has no collector");
270   sys::SmartScopedReader<true> Reader(*GCLock);
271   return *(*GCNames)[this];
272 }
273
274 void Function::setGC(const char *Str) {
275   sys::SmartScopedWriter<true> Writer(*GCLock);
276   if (!GCNamePool)
277     GCNamePool = new StringPool();
278   if (!GCNames)
279     GCNames = new DenseMap<const Function*,PooledStringPtr>();
280   (*GCNames)[this] = GCNamePool->intern(Str);
281 }
282
283 void Function::clearGC() {
284   sys::SmartScopedWriter<true> Writer(*GCLock);
285   if (GCNames) {
286     GCNames->erase(this);
287     if (GCNames->empty()) {
288       delete GCNames;
289       GCNames = 0;
290       if (GCNamePool->empty()) {
291         delete GCNamePool;
292         GCNamePool = 0;
293       }
294     }
295   }
296 }
297
298 /// copyAttributesFrom - copy all additional attributes (those not needed to
299 /// create a Function) from the Function Src to this one.
300 void Function::copyAttributesFrom(const GlobalValue *Src) {
301   assert(isa<Function>(Src) && "Expected a Function!");
302   GlobalValue::copyAttributesFrom(Src);
303   const Function *SrcF = cast<Function>(Src);
304   setCallingConv(SrcF->getCallingConv());
305   setAttributes(SrcF->getAttributes());
306   if (SrcF->hasGC())
307     setGC(SrcF->getGC());
308   else
309     clearGC();
310 }
311
312 /// getIntrinsicID - This method returns the ID number of the specified
313 /// function, or Intrinsic::not_intrinsic if the function is not an
314 /// intrinsic, or if the pointer is null.  This value is always defined to be
315 /// zero to allow easy checking for whether a function is intrinsic or not.  The
316 /// particular intrinsic functions which correspond to this value are defined in
317 /// llvm/Intrinsics.h.
318 ///
319 unsigned Function::getIntrinsicID() const {
320   const ValueName *ValName = this->getValueName();
321   if (!ValName)
322     return 0;
323   unsigned Len = ValName->getKeyLength();
324   const char *Name = ValName->getKeyData();
325   
326   if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
327       || Name[2] != 'v' || Name[3] != 'm')
328     return 0;  // All intrinsics start with 'llvm.'
329
330 #define GET_FUNCTION_RECOGNIZER
331 #include "llvm/Intrinsics.gen"
332 #undef GET_FUNCTION_RECOGNIZER
333   return 0;
334 }
335
336 std::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) { 
337   assert(id < num_intrinsics && "Invalid intrinsic ID!");
338   const char * const Table[] = {
339     "not_intrinsic",
340 #define GET_INTRINSIC_NAME_TABLE
341 #include "llvm/Intrinsics.gen"
342 #undef GET_INTRINSIC_NAME_TABLE
343   };
344   if (numTys == 0)
345     return Table[id];
346   std::string Result(Table[id]);
347   for (unsigned i = 0; i < numTys; ++i) {
348     if (const PointerType* PTyp = dyn_cast<PointerType>(Tys[i])) {
349       Result += ".p" + llvm::utostr(PTyp->getAddressSpace()) + 
350                 EVT::getEVT(PTyp->getElementType()).getEVTString();
351     }
352     else if (Tys[i])
353       Result += "." + EVT::getEVT(Tys[i]).getEVTString();
354   }
355   return Result;
356 }
357
358 const FunctionType *Intrinsic::getType(LLVMContext &Context,
359                                        ID id, const Type **Tys, 
360                                        unsigned numTys) {
361   const Type *ResultTy = NULL;
362   std::vector<const Type*> ArgTys;
363   bool IsVarArg = false;
364   
365 #define GET_INTRINSIC_GENERATOR
366 #include "llvm/Intrinsics.gen"
367 #undef GET_INTRINSIC_GENERATOR
368
369   return FunctionType::get(ResultTy, ArgTys, IsVarArg); 
370 }
371
372 bool Intrinsic::isOverloaded(ID id) {
373   const bool OTable[] = {
374     false,
375 #define GET_INTRINSIC_OVERLOAD_TABLE
376 #include "llvm/Intrinsics.gen"
377 #undef GET_INTRINSIC_OVERLOAD_TABLE
378   };
379   return OTable[id];
380 }
381
382 /// This defines the "Intrinsic::getAttributes(ID id)" method.
383 #define GET_INTRINSIC_ATTRIBUTES
384 #include "llvm/Intrinsics.gen"
385 #undef GET_INTRINSIC_ATTRIBUTES
386
387 Function *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys, 
388                                     unsigned numTys) {
389   // There can never be multiple globals with the same name of different types,
390   // because intrinsics must be a specific type.
391   return
392     cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys),
393                                           getType(M->getContext(),
394                                                   id, Tys, numTys)));
395 }
396
397 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
398 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
399 #include "llvm/Intrinsics.gen"
400 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
401
402   /// hasAddressTaken - returns true if there are any uses of this function
403   /// other than direct calls or invokes to it.
404 bool Function::hasAddressTaken() const {
405   for (Value::use_const_iterator I = use_begin(), E = use_end(); I != E; ++I) {
406     if (I.getOperandNo() != 0 ||
407         (!isa<CallInst>(*I) && !isa<InvokeInst>(*I)))
408       return true;
409   }
410   return false;
411 }
412
413 // vim: sw=2 ai