f3169e1c5424b3118023d57cec13eecb8b9aea35
[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/CodeGen/ValueTypes.h"
18 #include "llvm/Support/LeakDetector.h"
19 #include "llvm/Support/ManagedStatic.h"
20 #include "llvm/Support/StringPool.h"
21 #include "SymbolTableListTraitsImpl.h"
22 #include "llvm/ADT/BitVector.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/StringExtras.h"
25 using namespace llvm;
26
27 BasicBlock *ilist_traits<BasicBlock>::createSentinel() {
28   BasicBlock *Ret = new BasicBlock();
29   // This should not be garbage monitored.
30   LeakDetector::removeGarbageObject(Ret);
31   return Ret;
32 }
33
34 iplist<BasicBlock> &ilist_traits<BasicBlock>::getList(Function *F) {
35   return F->getBasicBlockList();
36 }
37
38 Argument *ilist_traits<Argument>::createSentinel() {
39   Argument *Ret = new Argument(Type::Int32Ty);
40   // This should not be garbage monitored.
41   LeakDetector::removeGarbageObject(Ret);
42   return Ret;
43 }
44
45 iplist<Argument> &ilist_traits<Argument>::getList(Function *F) {
46   return F->getArgumentList();
47 }
48
49 // Explicit instantiations of SymbolTableListTraits since some of the methods
50 // are not in the public header file...
51 template class SymbolTableListTraits<Argument, Function>;
52 template class SymbolTableListTraits<BasicBlock, Function>;
53
54 //===----------------------------------------------------------------------===//
55 // Argument Implementation
56 //===----------------------------------------------------------------------===//
57
58 Argument::Argument(const Type *Ty, const std::string &Name, Function *Par)
59   : Value(Ty, Value::ArgumentVal) {
60   Parent = 0;
61
62   // Make sure that we get added to a function
63   LeakDetector::addGarbageObject(this);
64
65   if (Par)
66     Par->getArgumentList().push_back(this);
67   setName(Name);
68 }
69
70 void Argument::setParent(Function *parent) {
71   if (getParent())
72     LeakDetector::addGarbageObject(this);
73   Parent = parent;
74   if (getParent())
75     LeakDetector::removeGarbageObject(this);
76 }
77
78 //===----------------------------------------------------------------------===//
79 // ParamAttrsList Implementation
80 //===----------------------------------------------------------------------===//
81
82 uint16_t
83 ParamAttrsList::getParamAttrs(uint16_t Index) const {
84   unsigned limit = attrs.size();
85   for (unsigned i = 0; i < limit && attrs[i].index <= Index; ++i)
86     if (attrs[i].index == Index)
87       return attrs[i].attrs;
88   return ParamAttr::None;
89 }
90
91 std::string 
92 ParamAttrsList::getParamAttrsText(uint16_t Attrs) {
93   std::string Result;
94   if (Attrs & ParamAttr::ZExt)
95     Result += "zeroext ";
96   if (Attrs & ParamAttr::SExt)
97     Result += "signext ";
98   if (Attrs & ParamAttr::NoReturn)
99     Result += "noreturn ";
100   if (Attrs & ParamAttr::NoUnwind)
101     Result += "nounwind ";
102   if (Attrs & ParamAttr::InReg)
103     Result += "inreg ";
104   if (Attrs & ParamAttr::NoAlias)
105     Result += "noalias ";
106   if (Attrs & ParamAttr::StructRet)
107     Result += "sret ";  
108   if (Attrs & ParamAttr::ByVal)
109     Result += "byval ";
110   if (Attrs & ParamAttr::Nest)
111     Result += "nest ";
112   if (Attrs & ParamAttr::ReadNone)
113     Result += "readnone ";
114   if (Attrs & ParamAttr::ReadOnly)
115     Result += "readonly ";
116   return Result;
117 }
118
119 /// onlyInformative - Returns whether only informative attributes are set.
120 static inline bool onlyInformative(uint16_t attrs) {
121   return !(attrs & ~ParamAttr::Informative);
122 }
123
124 bool
125 ParamAttrsList::areCompatible(const ParamAttrsList *A, const ParamAttrsList *B){
126   if (A == B)
127     return true;
128   unsigned ASize = A ? A->size() : 0;
129   unsigned BSize = B ? B->size() : 0;
130   unsigned AIndex = 0;
131   unsigned BIndex = 0;
132
133   while (AIndex < ASize && BIndex < BSize) {
134     uint16_t AIdx = A->getParamIndex(AIndex);
135     uint16_t BIdx = B->getParamIndex(BIndex);
136     uint16_t AAttrs = A->getParamAttrsAtIndex(AIndex);
137     uint16_t BAttrs = B->getParamAttrsAtIndex(AIndex);
138
139     if (AIdx < BIdx) {
140       if (!onlyInformative(AAttrs))
141         return false;
142       ++AIndex;
143     } else if (BIdx < AIdx) {
144       if (!onlyInformative(BAttrs))
145         return false;
146       ++BIndex;
147     } else {
148       if (!onlyInformative(AAttrs ^ BAttrs))
149         return false;
150       ++AIndex;
151       ++BIndex;
152     }
153   }
154   for (; AIndex < ASize; ++AIndex)
155     if (!onlyInformative(A->getParamAttrsAtIndex(AIndex)))
156       return false;
157   for (; BIndex < BSize; ++BIndex)
158     if (!onlyInformative(B->getParamAttrsAtIndex(AIndex)))
159       return false;
160   return true;
161 }
162
163 void ParamAttrsList::Profile(FoldingSetNodeID &ID) const {
164   for (unsigned i = 0; i < attrs.size(); ++i)
165     ID.AddInteger(unsigned(attrs[i].attrs) << 16 | unsigned(attrs[i].index));
166 }
167
168 static ManagedStatic<FoldingSet<ParamAttrsList> > ParamAttrsLists;
169
170 const ParamAttrsList *
171 ParamAttrsList::get(const ParamAttrsVector &attrVec) {
172   // If there are no attributes then return a null ParamAttrsList pointer.
173   if (attrVec.empty())
174     return 0;
175
176 #ifndef NDEBUG
177   for (unsigned i = 0, e = attrVec.size(); i < e; ++i) {
178     assert(attrVec[i].attrs != ParamAttr::None
179            && "Pointless parameter attribute!");
180     assert((!i || attrVec[i-1].index < attrVec[i].index)
181            && "Misordered ParamAttrsList!");
182   }
183 #endif
184
185   // Otherwise, build a key to look up the existing attributes.
186   ParamAttrsList key(attrVec);
187   FoldingSetNodeID ID;
188   key.Profile(ID);
189   void *InsertPos;
190   ParamAttrsList* PAL = ParamAttrsLists->FindNodeOrInsertPos(ID, InsertPos);
191
192   // If we didn't find any existing attributes of the same shape then
193   // create a new one and insert it.
194   if (!PAL) {
195     PAL = new ParamAttrsList(attrVec);
196     ParamAttrsLists->InsertNode(PAL, InsertPos);
197   }
198
199   // Return the ParamAttrsList that we found or created.
200   return PAL;
201 }
202
203 const ParamAttrsList *
204 ParamAttrsList::getModified(const ParamAttrsList *PAL,
205                             const ParamAttrsVector &modVec) {
206   if (modVec.empty())
207     return PAL;
208
209 #ifndef NDEBUG
210   for (unsigned i = 0, e = modVec.size(); i < e; ++i)
211     assert((!i || modVec[i-1].index < modVec[i].index)
212            && "Misordered ParamAttrsList!");
213 #endif
214
215   if (!PAL) {
216     // Strip any instances of ParamAttr::None from modVec before calling 'get'.
217     ParamAttrsVector newVec;
218     for (unsigned i = 0, e = modVec.size(); i < e; ++i)
219       if (modVec[i].attrs != ParamAttr::None)
220         newVec.push_back(modVec[i]);
221     return get(newVec);
222   }
223
224   const ParamAttrsVector &oldVec = PAL->attrs;
225
226   ParamAttrsVector newVec;
227   unsigned oldI = 0;
228   unsigned modI = 0;
229   unsigned oldE = oldVec.size();
230   unsigned modE = modVec.size();
231
232   while (oldI < oldE && modI < modE) {
233     uint16_t oldIndex = oldVec[oldI].index;
234     uint16_t modIndex = modVec[modI].index;
235
236     if (oldIndex < modIndex) {
237       newVec.push_back(oldVec[oldI]);
238       ++oldI;
239     } else if (modIndex < oldIndex) {
240       if (modVec[modI].attrs != ParamAttr::None)
241         newVec.push_back(modVec[modI]);
242       ++modI;
243     } else {
244       // Same index - overwrite or delete existing attributes.
245       if (modVec[modI].attrs != ParamAttr::None)
246         newVec.push_back(modVec[modI]);
247       ++oldI;
248       ++modI;
249     }
250   }
251
252   for (; oldI < oldE; ++oldI)
253     newVec.push_back(oldVec[oldI]);
254   for (; modI < modE; ++modI)
255     if (modVec[modI].attrs != ParamAttr::None)
256       newVec.push_back(modVec[modI]);
257
258   return get(newVec);
259 }
260
261 const ParamAttrsList *
262 ParamAttrsList::includeAttrs(const ParamAttrsList *PAL,
263                              uint16_t idx, uint16_t attrs) {
264   uint16_t OldAttrs = PAL ? PAL->getParamAttrs(idx) : 0;
265   uint16_t NewAttrs = OldAttrs | attrs;
266   if (NewAttrs == OldAttrs)
267     return PAL;
268
269   ParamAttrsVector modVec;
270   modVec.push_back(ParamAttrsWithIndex::get(idx, NewAttrs));
271   return getModified(PAL, modVec);
272 }
273
274 const ParamAttrsList *
275 ParamAttrsList::excludeAttrs(const ParamAttrsList *PAL,
276                              uint16_t idx, uint16_t attrs) {
277   uint16_t OldAttrs = PAL ? PAL->getParamAttrs(idx) : 0;
278   uint16_t NewAttrs = OldAttrs & ~attrs;
279   if (NewAttrs == OldAttrs)
280     return PAL;
281
282   ParamAttrsVector modVec;
283   modVec.push_back(ParamAttrsWithIndex::get(idx, NewAttrs));
284   return getModified(PAL, modVec);
285 }
286
287 ParamAttrsList::~ParamAttrsList() {
288   ParamAttrsLists->RemoveNode(this);
289 }
290
291 //===----------------------------------------------------------------------===//
292 // Function Implementation
293 //===----------------------------------------------------------------------===//
294
295 Function::Function(const FunctionType *Ty, LinkageTypes Linkage,
296                    const std::string &name, Module *ParentModule)
297   : GlobalValue(PointerType::getUnqual(Ty), 
298                 Value::FunctionVal, 0, 0, Linkage, name),
299     ParamAttrs(0) {
300   SymTab = new ValueSymbolTable();
301
302   assert((getReturnType()->isFirstClassType() ||getReturnType() == Type::VoidTy)
303          && "LLVM functions cannot return aggregate values!");
304
305   // If the function has arguments, mark them as lazily built.
306   if (Ty->getNumParams())
307     SubclassData = 1;   // Set the "has lazy arguments" bit.
308   
309   // Make sure that we get added to a function
310   LeakDetector::addGarbageObject(this);
311
312   if (ParentModule)
313     ParentModule->getFunctionList().push_back(this);
314 }
315
316 Function::~Function() {
317   dropAllReferences();    // After this it is safe to delete instructions.
318
319   // Delete all of the method arguments and unlink from symbol table...
320   ArgumentList.clear();
321   delete SymTab;
322
323   // Drop our reference to the parameter attributes, if any.
324   if (ParamAttrs)
325     ParamAttrs->dropRef();
326   
327   // Remove the function from the on-the-side collector table.
328   clearCollector();
329 }
330
331 void Function::BuildLazyArguments() const {
332   // Create the arguments vector, all arguments start out unnamed.
333   const FunctionType *FT = getFunctionType();
334   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
335     assert(FT->getParamType(i) != Type::VoidTy &&
336            "Cannot have void typed arguments!");
337     ArgumentList.push_back(new Argument(FT->getParamType(i)));
338   }
339   
340   // Clear the lazy arguments bit.
341   const_cast<Function*>(this)->SubclassData &= ~1;
342 }
343
344 size_t Function::arg_size() const {
345   return getFunctionType()->getNumParams();
346 }
347 bool Function::arg_empty() const {
348   return getFunctionType()->getNumParams() == 0;
349 }
350
351 void Function::setParent(Module *parent) {
352   if (getParent())
353     LeakDetector::addGarbageObject(this);
354   Parent = parent;
355   if (getParent())
356     LeakDetector::removeGarbageObject(this);
357 }
358
359 void Function::setParamAttrs(const ParamAttrsList *attrs) {
360   // Avoid deleting the ParamAttrsList if they are setting the
361   // attributes to the same list.
362   if (ParamAttrs == attrs)
363     return;
364
365   // Drop reference on the old ParamAttrsList
366   if (ParamAttrs)
367     ParamAttrs->dropRef();
368
369   // Add reference to the new ParamAttrsList
370   if (attrs)
371     attrs->addRef();
372
373   // Set the new ParamAttrsList.
374   ParamAttrs = attrs; 
375 }
376
377 const FunctionType *Function::getFunctionType() const {
378   return cast<FunctionType>(getType()->getElementType());
379 }
380
381 bool Function::isVarArg() const {
382   return getFunctionType()->isVarArg();
383 }
384
385 const Type *Function::getReturnType() const {
386   return getFunctionType()->getReturnType();
387 }
388
389 void Function::removeFromParent() {
390   getParent()->getFunctionList().remove(this);
391 }
392
393 void Function::eraseFromParent() {
394   getParent()->getFunctionList().erase(this);
395 }
396
397 // dropAllReferences() - This function causes all the subinstructions to "let
398 // go" of all references that they are maintaining.  This allows one to
399 // 'delete' a whole class at a time, even though there may be circular
400 // references... first all references are dropped, and all use counts go to
401 // zero.  Then everything is deleted for real.  Note that no operations are
402 // valid on an object that has "dropped all references", except operator
403 // delete.
404 //
405 void Function::dropAllReferences() {
406   for (iterator I = begin(), E = end(); I != E; ++I)
407     I->dropAllReferences();
408   BasicBlocks.clear();    // Delete all basic blocks...
409 }
410
411 // Maintain the collector name for each function in an on-the-side table. This
412 // saves allocating an additional word in Function for programs which do not use
413 // GC (i.e., most programs) at the cost of increased overhead for clients which
414 // do use GC.
415 static DenseMap<const Function*,PooledStringPtr> *CollectorNames;
416 static StringPool *CollectorNamePool;
417
418 bool Function::hasCollector() const {
419   return CollectorNames && CollectorNames->count(this);
420 }
421
422 const char *Function::getCollector() const {
423   assert(hasCollector() && "Function has no collector");
424   return *(*CollectorNames)[this];
425 }
426
427 void Function::setCollector(const char *Str) {
428   if (!CollectorNamePool)
429     CollectorNamePool = new StringPool();
430   if (!CollectorNames)
431     CollectorNames = new DenseMap<const Function*,PooledStringPtr>();
432   (*CollectorNames)[this] = CollectorNamePool->intern(Str);
433 }
434
435 void Function::clearCollector() {
436   if (CollectorNames) {
437     CollectorNames->erase(this);
438     if (CollectorNames->empty()) {
439       delete CollectorNames;
440       CollectorNames = 0;
441       if (CollectorNamePool->empty()) {
442         delete CollectorNamePool;
443         CollectorNamePool = 0;
444       }
445     }
446   }
447 }
448
449 /// getIntrinsicID - This method returns the ID number of the specified
450 /// function, or Intrinsic::not_intrinsic if the function is not an
451 /// intrinsic, or if the pointer is null.  This value is always defined to be
452 /// zero to allow easy checking for whether a function is intrinsic or not.  The
453 /// particular intrinsic functions which correspond to this value are defined in
454 /// llvm/Intrinsics.h.
455 ///
456 unsigned Function::getIntrinsicID(bool noAssert) const {
457   const ValueName *ValName = this->getValueName();
458   if (!ValName)
459     return 0;
460   unsigned Len = ValName->getKeyLength();
461   const char *Name = ValName->getKeyData();
462   
463   if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
464       || Name[2] != 'v' || Name[3] != 'm')
465     return 0;  // All intrinsics start with 'llvm.'
466
467   assert((Len != 5 || noAssert) && "'llvm.' is an invalid intrinsic name!");
468
469 #define GET_FUNCTION_RECOGNIZER
470 #include "llvm/Intrinsics.gen"
471 #undef GET_FUNCTION_RECOGNIZER
472   assert(noAssert && "Invalid LLVM intrinsic name");
473   return 0;
474 }
475
476 std::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) { 
477   assert(id < num_intrinsics && "Invalid intrinsic ID!");
478   const char * const Table[] = {
479     "not_intrinsic",
480 #define GET_INTRINSIC_NAME_TABLE
481 #include "llvm/Intrinsics.gen"
482 #undef GET_INTRINSIC_NAME_TABLE
483   };
484   if (numTys == 0)
485     return Table[id];
486   std::string Result(Table[id]);
487   for (unsigned i = 0; i < numTys; ++i) 
488     if (Tys[i])
489       Result += "." + MVT::getValueTypeString(MVT::getValueType(Tys[i]));
490   return Result;
491 }
492
493 const FunctionType *Intrinsic::getType(ID id, const Type **Tys, 
494                                        unsigned numTys) {
495   const Type *ResultTy = NULL;
496   std::vector<const Type*> ArgTys;
497   bool IsVarArg = false;
498   
499 #define GET_INTRINSIC_GENERATOR
500 #include "llvm/Intrinsics.gen"
501 #undef GET_INTRINSIC_GENERATOR
502
503   return FunctionType::get(ResultTy, ArgTys, IsVarArg); 
504 }
505
506 const ParamAttrsList *Intrinsic::getParamAttrs(ID id) {
507   static const ParamAttrsList *IntrinsicAttributes[Intrinsic::num_intrinsics];
508
509   if (IntrinsicAttributes[id])
510     return IntrinsicAttributes[id];
511
512   ParamAttrsVector Attrs;
513   uint16_t Attr = ParamAttr::None;
514
515 #define GET_INTRINSIC_ATTRIBUTES
516 #include "llvm/Intrinsics.gen"
517 #undef GET_INTRINSIC_ATTRIBUTES
518
519   // Intrinsics cannot throw exceptions.
520   Attr |= ParamAttr::NoUnwind;
521
522   Attrs.push_back(ParamAttrsWithIndex::get(0, Attr));
523   IntrinsicAttributes[id] = ParamAttrsList::get(Attrs);
524   return IntrinsicAttributes[id];
525 }
526
527 Function *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys, 
528                                     unsigned numTys) {
529   // There can never be multiple globals with the same name of different types,
530   // because intrinsics must be a specific type.
531   Function *F =
532     cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys),
533                                           getType(id, Tys, numTys)));
534   F->setParamAttrs(getParamAttrs(id));
535   return F;
536 }
537
538 Value *IntrinsicInst::StripPointerCasts(Value *Ptr) {
539   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
540     if (CE->getOpcode() == Instruction::BitCast) {
541       if (isa<PointerType>(CE->getOperand(0)->getType()))
542         return StripPointerCasts(CE->getOperand(0));
543     } else if (CE->getOpcode() == Instruction::GetElementPtr) {
544       for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
545         if (!CE->getOperand(i)->isNullValue())
546           return Ptr;
547       return StripPointerCasts(CE->getOperand(0));
548     }
549     return Ptr;
550   }
551
552   if (BitCastInst *CI = dyn_cast<BitCastInst>(Ptr)) {
553     if (isa<PointerType>(CI->getOperand(0)->getType()))
554       return StripPointerCasts(CI->getOperand(0));
555   } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
556     if (GEP->hasAllZeroIndices())
557       return StripPointerCasts(GEP->getOperand(0));
558   }
559   return Ptr;
560 }
561
562 // vim: sw=2 ai