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