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