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