constify array itself, don't iterate multiple times.
[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/CallSite.h"
20 #include "llvm/Support/InstIterator.h"
21 #include "llvm/Support/LeakDetector.h"
22 #include "llvm/Support/ManagedStatic.h"
23 #include "llvm/Support/StringPool.h"
24 #include "llvm/Support/RWMutex.h"
25 #include "llvm/Support/Threading.h"
26 #include "SymbolTableListTraitsImpl.h"
27 #include "llvm/ADT/DenseMap.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/StringExtras.h"
30 using namespace llvm;
31
32
33 // Explicit instantiations of SymbolTableListTraits since some of the methods
34 // are not in the public header file...
35 template class llvm::SymbolTableListTraits<Argument, Function>;
36 template class llvm::SymbolTableListTraits<BasicBlock, Function>;
37
38 //===----------------------------------------------------------------------===//
39 // Argument Implementation
40 //===----------------------------------------------------------------------===//
41
42 Argument::Argument(Type *Ty, const Twine &Name, Function *Par)
43   : Value(Ty, Value::ArgumentVal) {
44   Parent = 0;
45
46   // Make sure that we get added to a function
47   LeakDetector::addGarbageObject(this);
48
49   if (Par)
50     Par->getArgumentList().push_back(this);
51   setName(Name);
52 }
53
54 void Argument::setParent(Function *parent) {
55   if (getParent())
56     LeakDetector::addGarbageObject(this);
57   Parent = parent;
58   if (getParent())
59     LeakDetector::removeGarbageObject(this);
60 }
61
62 /// getArgNo - Return the index of this formal argument in its containing
63 /// function.  For example in "void foo(int a, float b)" a is 0 and b is 1. 
64 unsigned Argument::getArgNo() const {
65   const Function *F = getParent();
66   assert(F && "Argument is not in a function");
67   
68   Function::const_arg_iterator AI = F->arg_begin();
69   unsigned ArgIdx = 0;
70   for (; &*AI != this; ++AI)
71     ++ArgIdx;
72
73   return ArgIdx;
74 }
75
76 /// hasByValAttr - Return true if this argument has the byval attribute on it
77 /// in its containing function.
78 bool Argument::hasByValAttr() const {
79   if (!getType()->isPointerTy()) return false;
80   return getParent()->paramHasAttr(getArgNo()+1, Attribute::ByVal);
81 }
82
83 unsigned Argument::getParamAlignment() const {
84   assert(getType()->isPointerTy() && "Only pointers have alignments");
85   return getParent()->getParamAlignment(getArgNo()+1);
86   
87 }
88
89 /// hasNestAttr - Return true if this argument has the nest attribute on
90 /// it in its containing function.
91 bool Argument::hasNestAttr() const {
92   if (!getType()->isPointerTy()) return false;
93   return getParent()->paramHasAttr(getArgNo()+1, Attribute::Nest);
94 }
95
96 /// hasNoAliasAttr - Return true if this argument has the noalias attribute on
97 /// it in its containing function.
98 bool Argument::hasNoAliasAttr() const {
99   if (!getType()->isPointerTy()) return false;
100   return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoAlias);
101 }
102
103 /// hasNoCaptureAttr - Return true if this argument has the nocapture attribute
104 /// on it in its containing function.
105 bool Argument::hasNoCaptureAttr() const {
106   if (!getType()->isPointerTy()) return false;
107   return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoCapture);
108 }
109
110 /// hasSRetAttr - Return true if this argument has the sret attribute on
111 /// it in its containing function.
112 bool Argument::hasStructRetAttr() const {
113   if (!getType()->isPointerTy()) return false;
114   if (this != getParent()->arg_begin())
115     return false; // StructRet param must be first param
116   return getParent()->paramHasAttr(1, Attribute::StructRet);
117 }
118
119 /// addAttr - Add a Attribute to an argument
120 void Argument::addAttr(Attributes attr) {
121   getParent()->addAttribute(getArgNo() + 1, attr);
122 }
123
124 /// removeAttr - Remove a Attribute from an argument
125 void Argument::removeAttr(Attributes attr) {
126   getParent()->removeAttribute(getArgNo() + 1, attr);
127 }
128
129
130 //===----------------------------------------------------------------------===//
131 // Helper Methods in Function
132 //===----------------------------------------------------------------------===//
133
134 LLVMContext &Function::getContext() const {
135   return getType()->getContext();
136 }
137
138 FunctionType *Function::getFunctionType() const {
139   return cast<FunctionType>(getType()->getElementType());
140 }
141
142 bool Function::isVarArg() const {
143   return getFunctionType()->isVarArg();
144 }
145
146 Type *Function::getReturnType() const {
147   return getFunctionType()->getReturnType();
148 }
149
150 void Function::removeFromParent() {
151   getParent()->getFunctionList().remove(this);
152 }
153
154 void Function::eraseFromParent() {
155   getParent()->getFunctionList().erase(this);
156 }
157
158 //===----------------------------------------------------------------------===//
159 // Function Implementation
160 //===----------------------------------------------------------------------===//
161
162 Function::Function(FunctionType *Ty, LinkageTypes Linkage,
163                    const Twine &name, Module *ParentModule)
164   : GlobalValue(PointerType::getUnqual(Ty), 
165                 Value::FunctionVal, 0, 0, Linkage, name) {
166   assert(FunctionType::isValidReturnType(getReturnType()) &&
167          "invalid return type");
168   SymTab = new ValueSymbolTable();
169
170   // If the function has arguments, mark them as lazily built.
171   if (Ty->getNumParams())
172     setValueSubclassData(1);   // Set the "has lazy arguments" bit.
173   
174   // Make sure that we get added to a function
175   LeakDetector::addGarbageObject(this);
176
177   if (ParentModule)
178     ParentModule->getFunctionList().push_back(this);
179
180   // Ensure intrinsics have the right parameter attributes.
181   if (unsigned IID = getIntrinsicID())
182     setAttributes(Intrinsic::getAttributes(Intrinsic::ID(IID)));
183
184 }
185
186 Function::~Function() {
187   dropAllReferences();    // After this it is safe to delete instructions.
188
189   // Delete all of the method arguments and unlink from symbol table...
190   ArgumentList.clear();
191   delete SymTab;
192
193   // Remove the function from the on-the-side GC table.
194   clearGC();
195 }
196
197 void Function::BuildLazyArguments() const {
198   // Create the arguments vector, all arguments start out unnamed.
199   FunctionType *FT = getFunctionType();
200   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
201     assert(!FT->getParamType(i)->isVoidTy() &&
202            "Cannot have void typed arguments!");
203     ArgumentList.push_back(new Argument(FT->getParamType(i)));
204   }
205   
206   // Clear the lazy arguments bit.
207   unsigned SDC = getSubclassDataFromValue();
208   const_cast<Function*>(this)->setValueSubclassData(SDC &= ~1);
209 }
210
211 size_t Function::arg_size() const {
212   return getFunctionType()->getNumParams();
213 }
214 bool Function::arg_empty() const {
215   return getFunctionType()->getNumParams() == 0;
216 }
217
218 void Function::setParent(Module *parent) {
219   if (getParent())
220     LeakDetector::addGarbageObject(this);
221   Parent = parent;
222   if (getParent())
223     LeakDetector::removeGarbageObject(this);
224 }
225
226 // dropAllReferences() - This function causes all the subinstructions to "let
227 // go" of all references that they are maintaining.  This allows one to
228 // 'delete' a whole class at a time, even though there may be circular
229 // references... first all references are dropped, and all use counts go to
230 // zero.  Then everything is deleted for real.  Note that no operations are
231 // valid on an object that has "dropped all references", except operator
232 // delete.
233 //
234 void Function::dropAllReferences() {
235   for (iterator I = begin(), E = end(); I != E; ++I)
236     I->dropAllReferences();
237   
238   // Delete all basic blocks. They are now unused, except possibly by
239   // blockaddresses, but BasicBlock's destructor takes care of those.
240   while (!BasicBlocks.empty())
241     BasicBlocks.begin()->eraseFromParent();
242 }
243
244 void Function::addAttribute(unsigned i, Attributes attr) {
245   AttrListPtr PAL = getAttributes();
246   PAL = PAL.addAttr(i, attr);
247   setAttributes(PAL);
248 }
249
250 void Function::removeAttribute(unsigned i, Attributes attr) {
251   AttrListPtr PAL = getAttributes();
252   PAL = PAL.removeAttr(i, attr);
253   setAttributes(PAL);
254 }
255
256 // Maintain the GC name for each function in an on-the-side table. This saves
257 // allocating an additional word in Function for programs which do not use GC
258 // (i.e., most programs) at the cost of increased overhead for clients which do
259 // use GC.
260 static DenseMap<const Function*,PooledStringPtr> *GCNames;
261 static StringPool *GCNamePool;
262 static ManagedStatic<sys::SmartRWMutex<true> > GCLock;
263
264 bool Function::hasGC() const {
265   sys::SmartScopedReader<true> Reader(*GCLock);
266   return GCNames && GCNames->count(this);
267 }
268
269 const char *Function::getGC() const {
270   assert(hasGC() && "Function has no collector");
271   sys::SmartScopedReader<true> Reader(*GCLock);
272   return *(*GCNames)[this];
273 }
274
275 void Function::setGC(const char *Str) {
276   sys::SmartScopedWriter<true> Writer(*GCLock);
277   if (!GCNamePool)
278     GCNamePool = new StringPool();
279   if (!GCNames)
280     GCNames = new DenseMap<const Function*,PooledStringPtr>();
281   (*GCNames)[this] = GCNamePool->intern(Str);
282 }
283
284 void Function::clearGC() {
285   sys::SmartScopedWriter<true> Writer(*GCLock);
286   if (GCNames) {
287     GCNames->erase(this);
288     if (GCNames->empty()) {
289       delete GCNames;
290       GCNames = 0;
291       if (GCNamePool->empty()) {
292         delete GCNamePool;
293         GCNamePool = 0;
294       }
295     }
296   }
297 }
298
299 /// copyAttributesFrom - copy all additional attributes (those not needed to
300 /// create a Function) from the Function Src to this one.
301 void Function::copyAttributesFrom(const GlobalValue *Src) {
302   assert(isa<Function>(Src) && "Expected a Function!");
303   GlobalValue::copyAttributesFrom(Src);
304   const Function *SrcF = cast<Function>(Src);
305   setCallingConv(SrcF->getCallingConv());
306   setAttributes(SrcF->getAttributes());
307   if (SrcF->hasGC())
308     setGC(SrcF->getGC());
309   else
310     clearGC();
311 }
312
313 /// getIntrinsicID - This method returns the ID number of the specified
314 /// function, or Intrinsic::not_intrinsic if the function is not an
315 /// intrinsic, or if the pointer is null.  This value is always defined to be
316 /// zero to allow easy checking for whether a function is intrinsic or not.  The
317 /// particular intrinsic functions which correspond to this value are defined in
318 /// llvm/Intrinsics.h.
319 ///
320 unsigned Function::getIntrinsicID() const {
321   const ValueName *ValName = this->getValueName();
322   if (!ValName)
323     return 0;
324   unsigned Len = ValName->getKeyLength();
325   const char *Name = ValName->getKeyData();
326   
327   if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
328       || Name[2] != 'v' || Name[3] != 'm')
329     return 0;  // All intrinsics start with 'llvm.'
330
331 #define GET_FUNCTION_RECOGNIZER
332 #include "llvm/Intrinsics.gen"
333 #undef GET_FUNCTION_RECOGNIZER
334   return 0;
335 }
336
337 std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) {
338   assert(id < num_intrinsics && "Invalid intrinsic ID!");
339   static const char * const Table[] = {
340     "not_intrinsic",
341 #define GET_INTRINSIC_NAME_TABLE
342 #include "llvm/Intrinsics.gen"
343 #undef GET_INTRINSIC_NAME_TABLE
344   };
345   if (Tys.empty())
346     return Table[id];
347   std::string Result(Table[id]);
348   for (unsigned i = 0; i < Tys.size(); ++i) {
349     if (PointerType* PTyp = dyn_cast<PointerType>(Tys[i])) {
350       Result += ".p" + llvm::utostr(PTyp->getAddressSpace()) + 
351                 EVT::getEVT(PTyp->getElementType()).getEVTString();
352     }
353     else if (Tys[i])
354       Result += "." + EVT::getEVT(Tys[i]).getEVTString();
355   }
356   return Result;
357 }
358
359 FunctionType *Intrinsic::getType(LLVMContext &Context,
360                                        ID id, ArrayRef<Type*> Tys) {
361   Type *ResultTy = NULL;
362   std::vector<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   static 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, ArrayRef<Type*> Tys) {
388   // There can never be multiple globals with the same name of different types,
389   // because intrinsics must be a specific type.
390   return
391     cast<Function>(M->getOrInsertFunction(getName(id, Tys),
392                                           getType(M->getContext(), id, Tys)));
393 }
394
395 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
396 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
397 #include "llvm/Intrinsics.gen"
398 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
399
400 /// hasAddressTaken - returns true if there are any uses of this function
401 /// other than direct calls or invokes to it.
402 bool Function::hasAddressTaken(const User* *PutOffender) const {
403   for (Value::const_use_iterator I = use_begin(), E = use_end(); I != E; ++I) {
404     const User *U = *I;
405     if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
406       return PutOffender ? (*PutOffender = U, true) : true;
407     ImmutableCallSite CS(cast<Instruction>(U));
408     if (!CS.isCallee(I))
409       return PutOffender ? (*PutOffender = U, true) : true;
410   }
411   return false;
412 }
413
414 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
415 /// setjmp or other function that gcc recognizes as "returning twice".
416 ///
417 /// FIXME: Remove after <rdar://problem/8031714> is fixed.
418 /// FIXME: Is the above FIXME valid?
419 bool Function::callsFunctionThatReturnsTwice() const {
420   static const char *const ReturnsTwiceFns[] = {
421     "_setjmp",
422     "setjmp",
423     "sigsetjmp",
424     "setjmp_syscall",
425     "savectx",
426     "qsetjmp",
427     "vfork",
428     "getcontext"
429   };
430
431   for (const_inst_iterator I = inst_begin(this), E = inst_end(this); I != E;
432        ++I) {
433     const CallInst* callInst = dyn_cast<CallInst>(&*I);
434     if (!callInst)
435       continue;
436     if (callInst->canReturnTwice())
437       return true;
438
439     // check for known function names.
440     // FIXME: move this to clang.
441     Function *F = callInst->getCalledFunction();
442     if (!F)
443       continue;
444     StringRef Name = F->getName();
445     for (unsigned J = 0, e = array_lengthof(ReturnsTwiceFns); J != e; ++J) {
446       if (Name == ReturnsTwiceFns[J])
447         return true;
448     }
449   }
450
451   return false;
452 }
453
454 // vim: sw=2 ai