Push LLVMContexts through the IntegerType APIs.
[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   BasicBlocks.clear();    // Delete all basic blocks...
221 }
222
223 void Function::addAttribute(unsigned i, Attributes attr) {
224   AttrListPtr PAL = getAttributes();
225   PAL = PAL.addAttr(i, attr);
226   setAttributes(PAL);
227 }
228
229 void Function::removeAttribute(unsigned i, Attributes attr) {
230   AttrListPtr PAL = getAttributes();
231   PAL = PAL.removeAttr(i, attr);
232   setAttributes(PAL);
233 }
234
235 // Maintain the GC name for each function in an on-the-side table. This saves
236 // allocating an additional word in Function for programs which do not use GC
237 // (i.e., most programs) at the cost of increased overhead for clients which do
238 // use GC.
239 static DenseMap<const Function*,PooledStringPtr> *GCNames;
240 static StringPool *GCNamePool;
241 static ManagedStatic<sys::SmartRWMutex<true> > GCLock;
242
243 bool Function::hasGC() const {
244   sys::SmartScopedReader<true> Reader(*GCLock);
245   return GCNames && GCNames->count(this);
246 }
247
248 const char *Function::getGC() const {
249   assert(hasGC() && "Function has no collector");
250   sys::SmartScopedReader<true> Reader(*GCLock);
251   return *(*GCNames)[this];
252 }
253
254 void Function::setGC(const char *Str) {
255   sys::SmartScopedWriter<true> Writer(*GCLock);
256   if (!GCNamePool)
257     GCNamePool = new StringPool();
258   if (!GCNames)
259     GCNames = new DenseMap<const Function*,PooledStringPtr>();
260   (*GCNames)[this] = GCNamePool->intern(Str);
261 }
262
263 void Function::clearGC() {
264   sys::SmartScopedWriter<true> Writer(*GCLock);
265   if (GCNames) {
266     GCNames->erase(this);
267     if (GCNames->empty()) {
268       delete GCNames;
269       GCNames = 0;
270       if (GCNamePool->empty()) {
271         delete GCNamePool;
272         GCNamePool = 0;
273       }
274     }
275   }
276 }
277
278 /// copyAttributesFrom - copy all additional attributes (those not needed to
279 /// create a Function) from the Function Src to this one.
280 void Function::copyAttributesFrom(const GlobalValue *Src) {
281   assert(isa<Function>(Src) && "Expected a Function!");
282   GlobalValue::copyAttributesFrom(Src);
283   const Function *SrcF = cast<Function>(Src);
284   setCallingConv(SrcF->getCallingConv());
285   setAttributes(SrcF->getAttributes());
286   if (SrcF->hasGC())
287     setGC(SrcF->getGC());
288   else
289     clearGC();
290 }
291
292 /// getIntrinsicID - This method returns the ID number of the specified
293 /// function, or Intrinsic::not_intrinsic if the function is not an
294 /// intrinsic, or if the pointer is null.  This value is always defined to be
295 /// zero to allow easy checking for whether a function is intrinsic or not.  The
296 /// particular intrinsic functions which correspond to this value are defined in
297 /// llvm/Intrinsics.h.
298 ///
299 unsigned Function::getIntrinsicID() const {
300   const ValueName *ValName = this->getValueName();
301   if (!ValName)
302     return 0;
303   unsigned Len = ValName->getKeyLength();
304   const char *Name = ValName->getKeyData();
305   
306   if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
307       || Name[2] != 'v' || Name[3] != 'm')
308     return 0;  // All intrinsics start with 'llvm.'
309
310 #define GET_FUNCTION_RECOGNIZER
311 #include "llvm/Intrinsics.gen"
312 #undef GET_FUNCTION_RECOGNIZER
313   return 0;
314 }
315
316 std::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) { 
317   assert(id < num_intrinsics && "Invalid intrinsic ID!");
318   const char * const Table[] = {
319     "not_intrinsic",
320 #define GET_INTRINSIC_NAME_TABLE
321 #include "llvm/Intrinsics.gen"
322 #undef GET_INTRINSIC_NAME_TABLE
323   };
324   if (numTys == 0)
325     return Table[id];
326   std::string Result(Table[id]);
327   for (unsigned i = 0; i < numTys; ++i) {
328     if (const PointerType* PTyp = dyn_cast<PointerType>(Tys[i])) {
329       Result += ".p" + llvm::utostr(PTyp->getAddressSpace()) + 
330                 EVT::getEVT(PTyp->getElementType()).getEVTString();
331     }
332     else if (Tys[i])
333       Result += "." + EVT::getEVT(Tys[i]).getEVTString();
334   }
335   return Result;
336 }
337
338 const FunctionType *Intrinsic::getType(LLVMContext &Context,
339                                        ID id, const Type **Tys, 
340                                        unsigned numTys) {
341   const Type *ResultTy = NULL;
342   std::vector<const Type*> ArgTys;
343   bool IsVarArg = false;
344   
345 #define GET_INTRINSIC_GENERATOR
346 #include "llvm/Intrinsics.gen"
347 #undef GET_INTRINSIC_GENERATOR
348
349   return FunctionType::get(ResultTy, ArgTys, IsVarArg); 
350 }
351
352 bool Intrinsic::isOverloaded(ID id) {
353   const bool OTable[] = {
354     false,
355 #define GET_INTRINSIC_OVERLOAD_TABLE
356 #include "llvm/Intrinsics.gen"
357 #undef GET_INTRINSIC_OVERLOAD_TABLE
358   };
359   return OTable[id];
360 }
361
362 /// This defines the "Intrinsic::getAttributes(ID id)" method.
363 #define GET_INTRINSIC_ATTRIBUTES
364 #include "llvm/Intrinsics.gen"
365 #undef GET_INTRINSIC_ATTRIBUTES
366
367 Function *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys, 
368                                     unsigned numTys) {
369   // There can never be multiple globals with the same name of different types,
370   // because intrinsics must be a specific type.
371   return
372     cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys),
373                                           getType(M->getContext(),
374                                                   id, Tys, numTys)));
375 }
376
377 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
378 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
379 #include "llvm/Intrinsics.gen"
380 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
381
382   /// hasAddressTaken - returns true if there are any uses of this function
383   /// other than direct calls or invokes to it.
384 bool Function::hasAddressTaken() const {
385   for (Value::use_const_iterator I = use_begin(), E = use_end(); I != E; ++I) {
386     if (I.getOperandNo() != 0 ||
387         (!isa<CallInst>(*I) && !isa<InvokeInst>(*I)))
388       return true;
389   }
390   return false;
391 }
392
393 // vim: sw=2 ai