Genericize the intrinsics descriptor decoding a bit to make room
[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_INTRINSTIC_GENERATOR_GLOBAL
361 #include "llvm/Intrinsics.gen"
362 #undef GET_INTRINSTIC_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::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_ARG:
394   case IIT_EXTEND_VEC_ARG:
395   case IIT_TRUNC_VEC_ARG: {
396     unsigned ArgNo = NextElt == Infos.size() ? 0 : Infos[NextElt++];
397     assert(ArgNo < Tys.size() && "Not enough types specified!");
398     Type *T = Tys[ArgNo];
399    
400     if (Info == IIT_EXTEND_VEC_ARG)
401       T = VectorType::getExtendedElementVectorType(cast<VectorType>(T));
402     if (Info == IIT_TRUNC_VEC_ARG)
403       T = VectorType::getTruncatedElementVectorType(cast<VectorType>(T));
404     return T;
405   }
406   case IIT_STRUCT5: ++StructElts; // FALL THROUGH.
407   case IIT_STRUCT4: ++StructElts; // FALL THROUGH.
408   case IIT_STRUCT3: ++StructElts; // FALL THROUGH.
409   case IIT_STRUCT2: {
410     Type *Elts[5];
411     for (unsigned i = 0; i != StructElts; ++i)
412       Elts[i] = DecodeFixedType(NextElt, Infos, Tys, Context);
413     return StructType::get(Context, ArrayRef<Type*>(Elts, StructElts));
414   }
415   }
416   llvm_unreachable("unhandled");
417 }
418   
419
420 FunctionType *Intrinsic::getType(LLVMContext &Context,
421                                  ID id, ArrayRef<Type*> Tys) {
422   Type *ResultTy = 0;
423   SmallVector<Type*, 8> ArgTys;
424   
425   // Check to see if the intrinsic's type was expressible by the table.
426   unsigned TableVal = IIT_Table[id-1];
427   if (TableVal != ~0U) {
428     // Decode the TableVal into an array of IITValues.
429     SmallVector<unsigned char, 8> IITValues;
430     do {
431       IITValues.push_back(TableVal & 0xF);
432       TableVal >>= 4;
433     } while (TableVal);
434     
435     unsigned NextElt = 0;
436     ResultTy = DecodeFixedType(NextElt, IITValues, Tys, Context);
437     
438     while (NextElt != IITValues.size())
439       ArgTys.push_back(DecodeFixedType(NextElt, IITValues, Tys, Context));
440
441     return FunctionType::get(ResultTy, ArgTys, false); 
442   }
443   
444 #define GET_INTRINSIC_GENERATOR
445 #include "llvm/Intrinsics.gen"
446 #undef GET_INTRINSIC_GENERATOR
447
448   return FunctionType::get(ResultTy, ArgTys, false); 
449 }
450
451 bool Intrinsic::isOverloaded(ID id) {
452 #define GET_INTRINSIC_OVERLOAD_TABLE
453 #include "llvm/Intrinsics.gen"
454 #undef GET_INTRINSIC_OVERLOAD_TABLE
455 }
456
457 /// This defines the "Intrinsic::getAttributes(ID id)" method.
458 #define GET_INTRINSIC_ATTRIBUTES
459 #include "llvm/Intrinsics.gen"
460 #undef GET_INTRINSIC_ATTRIBUTES
461
462 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
463   // There can never be multiple globals with the same name of different types,
464   // because intrinsics must be a specific type.
465   return
466     cast<Function>(M->getOrInsertFunction(getName(id, Tys),
467                                           getType(M->getContext(), id, Tys)));
468 }
469
470 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
471 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
472 #include "llvm/Intrinsics.gen"
473 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
474
475 /// hasAddressTaken - returns true if there are any uses of this function
476 /// other than direct calls or invokes to it.
477 bool Function::hasAddressTaken(const User* *PutOffender) const {
478   for (Value::const_use_iterator I = use_begin(), E = use_end(); I != E; ++I) {
479     const User *U = *I;
480     if (isa<BlockAddress>(U))
481       continue;
482     if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
483       return PutOffender ? (*PutOffender = U, true) : true;
484     ImmutableCallSite CS(cast<Instruction>(U));
485     if (!CS.isCallee(I))
486       return PutOffender ? (*PutOffender = U, true) : true;
487   }
488   return false;
489 }
490
491 bool Function::isDefTriviallyDead() const {
492   // Check the linkage
493   if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
494       !hasAvailableExternallyLinkage())
495     return false;
496
497   // Check if the function is used by anything other than a blockaddress.
498   for (Value::const_use_iterator I = use_begin(), E = use_end(); I != E; ++I)
499     if (!isa<BlockAddress>(*I))
500       return false;
501
502   return true;
503 }
504
505 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
506 /// setjmp or other function that gcc recognizes as "returning twice".
507 bool Function::callsFunctionThatReturnsTwice() const {
508   for (const_inst_iterator
509          I = inst_begin(this), E = inst_end(this); I != E; ++I) {
510     const CallInst* callInst = dyn_cast<CallInst>(&*I);
511     if (!callInst)
512       continue;
513     if (callInst->canReturnTwice())
514       return true;
515   }
516
517   return false;
518 }
519