enhance the intrinsic info table to encode what *kind* of Any argument
[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 // 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 void Argument::anchor() { }
42
43 Argument::Argument(Type *Ty, const Twine &Name, Function *Par)
44   : Value(Ty, Value::ArgumentVal) {
45   Parent = 0;
46
47   // Make sure that we get added to a function
48   LeakDetector::addGarbageObject(this);
49
50   if (Par)
51     Par->getArgumentList().push_back(this);
52   setName(Name);
53 }
54
55 void Argument::setParent(Function *parent) {
56   if (getParent())
57     LeakDetector::addGarbageObject(this);
58   Parent = parent;
59   if (getParent())
60     LeakDetector::removeGarbageObject(this);
61 }
62
63 /// getArgNo - Return the index of this formal argument in its containing
64 /// function.  For example in "void foo(int a, float b)" a is 0 and b is 1. 
65 unsigned Argument::getArgNo() const {
66   const Function *F = getParent();
67   assert(F && "Argument is not in a function");
68   
69   Function::const_arg_iterator AI = F->arg_begin();
70   unsigned ArgIdx = 0;
71   for (; &*AI != this; ++AI)
72     ++ArgIdx;
73
74   return ArgIdx;
75 }
76
77 /// hasByValAttr - Return true if this argument has the byval attribute on it
78 /// in its containing function.
79 bool Argument::hasByValAttr() const {
80   if (!getType()->isPointerTy()) return false;
81   return getParent()->paramHasAttr(getArgNo()+1, Attribute::ByVal);
82 }
83
84 unsigned Argument::getParamAlignment() const {
85   assert(getType()->isPointerTy() && "Only pointers have alignments");
86   return getParent()->getParamAlignment(getArgNo()+1);
87   
88 }
89
90 /// hasNestAttr - Return true if this argument has the nest attribute on
91 /// it in its containing function.
92 bool Argument::hasNestAttr() const {
93   if (!getType()->isPointerTy()) return false;
94   return getParent()->paramHasAttr(getArgNo()+1, Attribute::Nest);
95 }
96
97 /// hasNoAliasAttr - Return true if this argument has the noalias attribute on
98 /// it in its containing function.
99 bool Argument::hasNoAliasAttr() const {
100   if (!getType()->isPointerTy()) return false;
101   return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoAlias);
102 }
103
104 /// hasNoCaptureAttr - Return true if this argument has the nocapture attribute
105 /// on it in its containing function.
106 bool Argument::hasNoCaptureAttr() const {
107   if (!getType()->isPointerTy()) return false;
108   return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoCapture);
109 }
110
111 /// hasSRetAttr - Return true if this argument has the sret attribute on
112 /// it in its containing function.
113 bool Argument::hasStructRetAttr() const {
114   if (!getType()->isPointerTy()) return false;
115   if (this != getParent()->arg_begin())
116     return false; // StructRet param must be first param
117   return getParent()->paramHasAttr(1, Attribute::StructRet);
118 }
119
120 /// addAttr - Add a Attribute to an argument
121 void Argument::addAttr(Attributes attr) {
122   getParent()->addAttribute(getArgNo() + 1, attr);
123 }
124
125 /// removeAttr - Remove a Attribute from an argument
126 void Argument::removeAttr(Attributes attr) {
127   getParent()->removeAttribute(getArgNo() + 1, attr);
128 }
129
130
131 //===----------------------------------------------------------------------===//
132 // Helper Methods in Function
133 //===----------------------------------------------------------------------===//
134
135 LLVMContext &Function::getContext() const {
136   return getType()->getContext();
137 }
138
139 FunctionType *Function::getFunctionType() const {
140   return cast<FunctionType>(getType()->getElementType());
141 }
142
143 bool Function::isVarArg() const {
144   return getFunctionType()->isVarArg();
145 }
146
147 Type *Function::getReturnType() const {
148   return getFunctionType()->getReturnType();
149 }
150
151 void Function::removeFromParent() {
152   getParent()->getFunctionList().remove(this);
153 }
154
155 void Function::eraseFromParent() {
156   getParent()->getFunctionList().erase(this);
157 }
158
159 //===----------------------------------------------------------------------===//
160 // Function Implementation
161 //===----------------------------------------------------------------------===//
162
163 Function::Function(FunctionType *Ty, LinkageTypes Linkage,
164                    const Twine &name, Module *ParentModule)
165   : GlobalValue(PointerType::getUnqual(Ty), 
166                 Value::FunctionVal, 0, 0, Linkage, name) {
167   assert(FunctionType::isValidReturnType(getReturnType()) &&
168          "invalid return type");
169   SymTab = new ValueSymbolTable();
170
171   // If the function has arguments, mark them as lazily built.
172   if (Ty->getNumParams())
173     setValueSubclassData(1);   // Set the "has lazy arguments" bit.
174   
175   // Make sure that we get added to a function
176   LeakDetector::addGarbageObject(this);
177
178   if (ParentModule)
179     ParentModule->getFunctionList().push_back(this);
180
181   // Ensure intrinsics have the right parameter attributes.
182   if (unsigned IID = getIntrinsicID())
183     setAttributes(Intrinsic::getAttributes(Intrinsic::ID(IID)));
184
185 }
186
187 Function::~Function() {
188   dropAllReferences();    // After this it is safe to delete instructions.
189
190   // Delete all of the method arguments and unlink from symbol table...
191   ArgumentList.clear();
192   delete SymTab;
193
194   // Remove the function from the on-the-side GC table.
195   clearGC();
196 }
197
198 void Function::BuildLazyArguments() const {
199   // Create the arguments vector, all arguments start out unnamed.
200   FunctionType *FT = getFunctionType();
201   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
202     assert(!FT->getParamType(i)->isVoidTy() &&
203            "Cannot have void typed arguments!");
204     ArgumentList.push_back(new Argument(FT->getParamType(i)));
205   }
206   
207   // Clear the lazy arguments bit.
208   unsigned SDC = getSubclassDataFromValue();
209   const_cast<Function*>(this)->setValueSubclassData(SDC &= ~1);
210 }
211
212 size_t Function::arg_size() const {
213   return getFunctionType()->getNumParams();
214 }
215 bool Function::arg_empty() const {
216   return getFunctionType()->getNumParams() == 0;
217 }
218
219 void Function::setParent(Module *parent) {
220   if (getParent())
221     LeakDetector::addGarbageObject(this);
222   Parent = parent;
223   if (getParent())
224     LeakDetector::removeGarbageObject(this);
225 }
226
227 // dropAllReferences() - This function causes all the subinstructions to "let
228 // go" of all references that they are maintaining.  This allows one to
229 // 'delete' a whole class at a time, even though there may be circular
230 // references... first all references are dropped, and all use counts go to
231 // zero.  Then everything is deleted for real.  Note that no operations are
232 // valid on an object that has "dropped all references", except operator
233 // delete.
234 //
235 void Function::dropAllReferences() {
236   for (iterator I = begin(), E = end(); I != E; ++I)
237     I->dropAllReferences();
238   
239   // Delete all basic blocks. They are now unused, except possibly by
240   // blockaddresses, but BasicBlock's destructor takes care of those.
241   while (!BasicBlocks.empty())
242     BasicBlocks.begin()->eraseFromParent();
243 }
244
245 void Function::addAttribute(unsigned i, Attributes attr) {
246   AttrListPtr PAL = getAttributes();
247   PAL = PAL.addAttr(i, attr);
248   setAttributes(PAL);
249 }
250
251 void Function::removeAttribute(unsigned i, Attributes attr) {
252   AttrListPtr PAL = getAttributes();
253   PAL = PAL.removeAttr(i, attr);
254   setAttributes(PAL);
255 }
256
257 // Maintain the GC name for each function in an on-the-side table. This saves
258 // allocating an additional word in Function for programs which do not use GC
259 // (i.e., most programs) at the cost of increased overhead for clients which do
260 // use GC.
261 static DenseMap<const Function*,PooledStringPtr> *GCNames;
262 static StringPool *GCNamePool;
263 static ManagedStatic<sys::SmartRWMutex<true> > GCLock;
264
265 bool Function::hasGC() const {
266   sys::SmartScopedReader<true> Reader(*GCLock);
267   return GCNames && GCNames->count(this);
268 }
269
270 const char *Function::getGC() const {
271   assert(hasGC() && "Function has no collector");
272   sys::SmartScopedReader<true> Reader(*GCLock);
273   return *(*GCNames)[this];
274 }
275
276 void Function::setGC(const char *Str) {
277   sys::SmartScopedWriter<true> Writer(*GCLock);
278   if (!GCNamePool)
279     GCNamePool = new StringPool();
280   if (!GCNames)
281     GCNames = new DenseMap<const Function*,PooledStringPtr>();
282   (*GCNames)[this] = GCNamePool->intern(Str);
283 }
284
285 void Function::clearGC() {
286   sys::SmartScopedWriter<true> Writer(*GCLock);
287   if (GCNames) {
288     GCNames->erase(this);
289     if (GCNames->empty()) {
290       delete GCNames;
291       GCNames = 0;
292       if (GCNamePool->empty()) {
293         delete GCNamePool;
294         GCNamePool = 0;
295       }
296     }
297   }
298 }
299
300 /// copyAttributesFrom - copy all additional attributes (those not needed to
301 /// create a Function) from the Function Src to this one.
302 void Function::copyAttributesFrom(const GlobalValue *Src) {
303   assert(isa<Function>(Src) && "Expected a Function!");
304   GlobalValue::copyAttributesFrom(Src);
305   const Function *SrcF = cast<Function>(Src);
306   setCallingConv(SrcF->getCallingConv());
307   setAttributes(SrcF->getAttributes());
308   if (SrcF->hasGC())
309     setGC(SrcF->getGC());
310   else
311     clearGC();
312 }
313
314 /// getIntrinsicID - This method returns the ID number of the specified
315 /// function, or Intrinsic::not_intrinsic if the function is not an
316 /// intrinsic, or if the pointer is null.  This value is always defined to be
317 /// zero to allow easy checking for whether a function is intrinsic or not.  The
318 /// particular intrinsic functions which correspond to this value are defined in
319 /// llvm/Intrinsics.h.
320 ///
321 unsigned Function::getIntrinsicID() const {
322   const ValueName *ValName = this->getValueName();
323   if (!ValName)
324     return 0;
325   unsigned Len = ValName->getKeyLength();
326   const char *Name = ValName->getKeyData();
327   
328   if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
329       || Name[2] != 'v' || Name[3] != 'm')
330     return 0;  // All intrinsics start with 'llvm.'
331
332 #define GET_FUNCTION_RECOGNIZER
333 #include "llvm/Intrinsics.gen"
334 #undef GET_FUNCTION_RECOGNIZER
335   return 0;
336 }
337
338 std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) {
339   assert(id < num_intrinsics && "Invalid intrinsic ID!");
340   static const char * const Table[] = {
341     "not_intrinsic",
342 #define GET_INTRINSIC_NAME_TABLE
343 #include "llvm/Intrinsics.gen"
344 #undef GET_INTRINSIC_NAME_TABLE
345   };
346   if (Tys.empty())
347     return Table[id];
348   std::string Result(Table[id]);
349   for (unsigned i = 0; i < Tys.size(); ++i) {
350     if (PointerType* PTyp = dyn_cast<PointerType>(Tys[i])) {
351       Result += ".p" + llvm::utostr(PTyp->getAddressSpace()) + 
352                 EVT::getEVT(PTyp->getElementType()).getEVTString();
353     }
354     else if (Tys[i])
355       Result += "." + EVT::getEVT(Tys[i]).getEVTString();
356   }
357   return Result;
358 }
359
360 #define GET_INTRINSIC_GENERATOR_GLOBAL
361 #include "llvm/Intrinsics.gen"
362 #undef GET_INTRINSIC_GENERATOR_GLOBAL
363
364 static Type *DecodeFixedType(unsigned &NextElt, ArrayRef<unsigned char> Infos,
365                              ArrayRef<Type*> Tys, LLVMContext &Context) {
366   IIT_Info Info = IIT_Info(Infos[NextElt++]);
367   unsigned StructElts = 2;
368   
369   switch (Info) {
370   case IIT_Done: return Type::getVoidTy(Context);
371   case IIT_I1: return Type::getInt1Ty(Context);
372   case IIT_I8: return Type::getInt8Ty(Context);
373   case IIT_I16: return Type::getInt16Ty(Context);
374   case IIT_I32: return Type::getInt32Ty(Context);
375   case IIT_I64: return Type::getInt64Ty(Context);
376   case IIT_F32: return Type::getFloatTy(Context);
377   case IIT_F64: return Type::getDoubleTy(Context);
378   case IIT_MMX: return Type::getX86_MMXTy(Context);
379   case IIT_METADATA: return Type::getMetadataTy(Context);
380   case IIT_EMPTYSTRUCT: return StructType::get(Context);
381   case IIT_V2:
382     return VectorType::get(DecodeFixedType(NextElt, Infos, Tys, Context), 2);
383   case IIT_V4:
384     return VectorType::get(DecodeFixedType(NextElt, Infos, Tys, Context), 4);
385   case IIT_V8:
386     return VectorType::get(DecodeFixedType(NextElt, Infos, Tys, Context), 8);
387   case IIT_V16:
388     return VectorType::get(DecodeFixedType(NextElt, Infos, Tys, Context), 16);
389   case IIT_V32:
390     return VectorType::get(DecodeFixedType(NextElt, Infos, Tys, Context), 32);
391   case IIT_PTR:
392     return PointerType::getUnqual(DecodeFixedType(NextElt, Infos, Tys,Context));
393   case IIT_ANYPTR: {  // [ANYPTR addrspace, subtype]
394     unsigned AddrSpace = Infos[NextElt++];
395     Type *PtrTy = DecodeFixedType(NextElt, Infos, Tys,Context);
396     return PointerType::get(PtrTy, AddrSpace);
397   }
398   case IIT_ARG:
399   case IIT_EXTEND_VEC_ARG:
400   case IIT_TRUNC_VEC_ARG: {
401     unsigned ArgNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]) >> 2;
402     assert(ArgNo < Tys.size() && "Not enough types specified!");
403     Type *T = Tys[ArgNo];
404    
405     if (Info == IIT_EXTEND_VEC_ARG)
406       T = VectorType::getExtendedElementVectorType(cast<VectorType>(T));
407     if (Info == IIT_TRUNC_VEC_ARG)
408       T = VectorType::getTruncatedElementVectorType(cast<VectorType>(T));
409     return T;
410   }
411   case IIT_STRUCT5: ++StructElts; // FALL THROUGH.
412   case IIT_STRUCT4: ++StructElts; // FALL THROUGH.
413   case IIT_STRUCT3: ++StructElts; // FALL THROUGH.
414   case IIT_STRUCT2: {
415     Type *Elts[5];
416     for (unsigned i = 0; i != StructElts; ++i)
417       Elts[i] = DecodeFixedType(NextElt, Infos, Tys, Context);
418     return StructType::get(Context, ArrayRef<Type*>(Elts, StructElts));
419   }
420   }
421   llvm_unreachable("unhandled");
422 }
423   
424
425 FunctionType *Intrinsic::getType(LLVMContext &Context,
426                                  ID id, ArrayRef<Type*> Tys) {
427   // Check to see if the intrinsic's type was expressible by the table.
428   unsigned TableVal = IIT_Table[id-1];
429   
430   // Decode the TableVal into an array of IITValues.
431   SmallVector<unsigned char, 8> IITValues;
432   ArrayRef<unsigned char> IITEntries;
433   unsigned NextElt = 0;
434   if ((TableVal >> 31) != 0) {
435     // This is an offset into the IIT_LongEncodingTable.
436     IITEntries = IIT_LongEncodingTable;
437     
438     // Strip sentinel bit.
439     NextElt = (TableVal << 1) >> 1;
440   } else {
441     do {
442       IITValues.push_back(TableVal & 0xF);
443       TableVal >>= 4;
444     } while (TableVal);
445     
446     IITEntries = IITValues;
447     NextElt = 0;
448   }
449     
450   Type *ResultTy = DecodeFixedType(NextElt, IITEntries, Tys, Context);
451     
452   SmallVector<Type*, 8> ArgTys;
453   while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0)
454     ArgTys.push_back(DecodeFixedType(NextElt, IITEntries, Tys, Context));
455
456   return FunctionType::get(ResultTy, ArgTys, false); 
457 }
458
459 bool Intrinsic::isOverloaded(ID id) {
460 #define GET_INTRINSIC_OVERLOAD_TABLE
461 #include "llvm/Intrinsics.gen"
462 #undef GET_INTRINSIC_OVERLOAD_TABLE
463 }
464
465 /// This defines the "Intrinsic::getAttributes(ID id)" method.
466 #define GET_INTRINSIC_ATTRIBUTES
467 #include "llvm/Intrinsics.gen"
468 #undef GET_INTRINSIC_ATTRIBUTES
469
470 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
471   // There can never be multiple globals with the same name of different types,
472   // because intrinsics must be a specific type.
473   return
474     cast<Function>(M->getOrInsertFunction(getName(id, Tys),
475                                           getType(M->getContext(), id, Tys)));
476 }
477
478 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
479 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
480 #include "llvm/Intrinsics.gen"
481 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
482
483 /// hasAddressTaken - returns true if there are any uses of this function
484 /// other than direct calls or invokes to it.
485 bool Function::hasAddressTaken(const User* *PutOffender) const {
486   for (Value::const_use_iterator I = use_begin(), E = use_end(); I != E; ++I) {
487     const User *U = *I;
488     if (isa<BlockAddress>(U))
489       continue;
490     if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
491       return PutOffender ? (*PutOffender = U, true) : true;
492     ImmutableCallSite CS(cast<Instruction>(U));
493     if (!CS.isCallee(I))
494       return PutOffender ? (*PutOffender = U, true) : true;
495   }
496   return false;
497 }
498
499 bool Function::isDefTriviallyDead() const {
500   // Check the linkage
501   if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
502       !hasAvailableExternallyLinkage())
503     return false;
504
505   // Check if the function is used by anything other than a blockaddress.
506   for (Value::const_use_iterator I = use_begin(), E = use_end(); I != E; ++I)
507     if (!isa<BlockAddress>(*I))
508       return false;
509
510   return true;
511 }
512
513 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
514 /// setjmp or other function that gcc recognizes as "returning twice".
515 bool Function::callsFunctionThatReturnsTwice() const {
516   for (const_inst_iterator
517          I = inst_begin(this), E = inst_end(this); I != E; ++I) {
518     const CallInst* callInst = dyn_cast<CallInst>(&*I);
519     if (!callInst)
520       continue;
521     if (callInst->canReturnTwice())
522       return true;
523   }
524
525   return false;
526 }
527