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