Remove attribution from file headers, per discussion on llvmdev.
[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 
164 ParamAttrsList::Profile(FoldingSetNodeID &ID) const {
165   for (unsigned i = 0; i < attrs.size(); ++i) {
166     uint32_t val = uint32_t(attrs[i].attrs) << 16 | attrs[i].index;
167     ID.AddInteger(val);
168   }
169 }
170
171 static ManagedStatic<FoldingSet<ParamAttrsList> > ParamAttrsLists;
172
173 const ParamAttrsList *
174 ParamAttrsList::get(const ParamAttrsVector &attrVec) {
175   // If there are no attributes then return a null ParamAttrsList pointer.
176   if (attrVec.empty())
177     return 0;
178
179 #ifndef NDEBUG
180   for (unsigned i = 0, e = attrVec.size(); i < e; ++i) {
181     assert(attrVec[i].attrs != ParamAttr::None
182            && "Pointless parameter attribute!");
183     assert((!i || attrVec[i-1].index < attrVec[i].index)
184            && "Misordered ParamAttrsList!");
185   }
186 #endif
187
188   // Otherwise, build a key to look up the existing attributes.
189   ParamAttrsList key(attrVec);
190   FoldingSetNodeID ID;
191   key.Profile(ID);
192   void *InsertPos;
193   ParamAttrsList* PAL = ParamAttrsLists->FindNodeOrInsertPos(ID, InsertPos);
194
195   // If we didn't find any existing attributes of the same shape then
196   // create a new one and insert it.
197   if (!PAL) {
198     PAL = new ParamAttrsList(attrVec);
199     ParamAttrsLists->InsertNode(PAL, InsertPos);
200   }
201
202   // Return the ParamAttrsList that we found or created.
203   return PAL;
204 }
205
206 const ParamAttrsList *
207 ParamAttrsList::getModified(const ParamAttrsList *PAL,
208                             const ParamAttrsVector &modVec) {
209   if (modVec.empty())
210     return PAL;
211
212 #ifndef NDEBUG
213   for (unsigned i = 0, e = modVec.size(); i < e; ++i)
214     assert((!i || modVec[i-1].index < modVec[i].index)
215            && "Misordered ParamAttrsList!");
216 #endif
217
218   if (!PAL) {
219     // Strip any instances of ParamAttr::None from modVec before calling 'get'.
220     ParamAttrsVector newVec;
221     for (unsigned i = 0, e = modVec.size(); i < e; ++i)
222       if (modVec[i].attrs != ParamAttr::None)
223         newVec.push_back(modVec[i]);
224     return get(newVec);
225   }
226
227   const ParamAttrsVector &oldVec = PAL->attrs;
228
229   ParamAttrsVector newVec;
230   unsigned oldI = 0;
231   unsigned modI = 0;
232   unsigned oldE = oldVec.size();
233   unsigned modE = modVec.size();
234
235   while (oldI < oldE && modI < modE) {
236     uint16_t oldIndex = oldVec[oldI].index;
237     uint16_t modIndex = modVec[modI].index;
238
239     if (oldIndex < modIndex) {
240       newVec.push_back(oldVec[oldI]);
241       ++oldI;
242     } else if (modIndex < oldIndex) {
243       if (modVec[modI].attrs != ParamAttr::None)
244         newVec.push_back(modVec[modI]);
245       ++modI;
246     } else {
247       // Same index - overwrite or delete existing attributes.
248       if (modVec[modI].attrs != ParamAttr::None)
249         newVec.push_back(modVec[modI]);
250       ++oldI;
251       ++modI;
252     }
253   }
254
255   for (; oldI < oldE; ++oldI)
256     newVec.push_back(oldVec[oldI]);
257   for (; modI < modE; ++modI)
258     if (modVec[modI].attrs != ParamAttr::None)
259       newVec.push_back(modVec[modI]);
260
261   return get(newVec);
262 }
263
264 const ParamAttrsList *
265 ParamAttrsList::includeAttrs(const ParamAttrsList *PAL,
266                              uint16_t idx, uint16_t attrs) {
267   uint16_t OldAttrs = PAL ? PAL->getParamAttrs(idx) : 0;
268   uint16_t NewAttrs = OldAttrs | attrs;
269   if (NewAttrs == OldAttrs)
270     return PAL;
271
272   ParamAttrsVector modVec;
273   modVec.push_back(ParamAttrsWithIndex::get(idx, NewAttrs));
274   return getModified(PAL, modVec);
275 }
276
277 const ParamAttrsList *
278 ParamAttrsList::excludeAttrs(const ParamAttrsList *PAL,
279                              uint16_t idx, uint16_t attrs) {
280   uint16_t OldAttrs = PAL ? PAL->getParamAttrs(idx) : 0;
281   uint16_t NewAttrs = OldAttrs & ~attrs;
282   if (NewAttrs == OldAttrs)
283     return PAL;
284
285   ParamAttrsVector modVec;
286   modVec.push_back(ParamAttrsWithIndex::get(idx, NewAttrs));
287   return getModified(PAL, modVec);
288 }
289
290 ParamAttrsList::~ParamAttrsList() {
291   ParamAttrsLists->RemoveNode(this);
292 }
293
294 //===----------------------------------------------------------------------===//
295 // Function Implementation
296 //===----------------------------------------------------------------------===//
297
298 Function::Function(const FunctionType *Ty, LinkageTypes Linkage,
299                    const std::string &name, Module *ParentModule)
300   : GlobalValue(PointerType::getUnqual(Ty), 
301                 Value::FunctionVal, 0, 0, Linkage, name),
302     ParamAttrs(0) {
303   SymTab = new ValueSymbolTable();
304
305   assert((getReturnType()->isFirstClassType() ||getReturnType() == Type::VoidTy)
306          && "LLVM functions cannot return aggregate values!");
307
308   // If the function has arguments, mark them as lazily built.
309   if (Ty->getNumParams())
310     SubclassData = 1;   // Set the "has lazy arguments" bit.
311   
312   // Make sure that we get added to a function
313   LeakDetector::addGarbageObject(this);
314
315   if (ParentModule)
316     ParentModule->getFunctionList().push_back(this);
317 }
318
319 Function::~Function() {
320   dropAllReferences();    // After this it is safe to delete instructions.
321
322   // Delete all of the method arguments and unlink from symbol table...
323   ArgumentList.clear();
324   delete SymTab;
325
326   // Drop our reference to the parameter attributes, if any.
327   if (ParamAttrs)
328     ParamAttrs->dropRef();
329   
330   // Remove the function from the on-the-side collector table.
331   clearCollector();
332 }
333
334 void Function::BuildLazyArguments() const {
335   // Create the arguments vector, all arguments start out unnamed.
336   const FunctionType *FT = getFunctionType();
337   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
338     assert(FT->getParamType(i) != Type::VoidTy &&
339            "Cannot have void typed arguments!");
340     ArgumentList.push_back(new Argument(FT->getParamType(i)));
341   }
342   
343   // Clear the lazy arguments bit.
344   const_cast<Function*>(this)->SubclassData &= ~1;
345 }
346
347 size_t Function::arg_size() const {
348   return getFunctionType()->getNumParams();
349 }
350 bool Function::arg_empty() const {
351   return getFunctionType()->getNumParams() == 0;
352 }
353
354 void Function::setParent(Module *parent) {
355   if (getParent())
356     LeakDetector::addGarbageObject(this);
357   Parent = parent;
358   if (getParent())
359     LeakDetector::removeGarbageObject(this);
360 }
361
362 void Function::setParamAttrs(const ParamAttrsList *attrs) {
363   // Avoid deleting the ParamAttrsList if they are setting the
364   // attributes to the same list.
365   if (ParamAttrs == attrs)
366     return;
367
368   // Drop reference on the old ParamAttrsList
369   if (ParamAttrs)
370     ParamAttrs->dropRef();
371
372   // Add reference to the new ParamAttrsList
373   if (attrs)
374     attrs->addRef();
375
376   // Set the new ParamAttrsList.
377   ParamAttrs = attrs; 
378 }
379
380 const FunctionType *Function::getFunctionType() const {
381   return cast<FunctionType>(getType()->getElementType());
382 }
383
384 bool Function::isVarArg() const {
385   return getFunctionType()->isVarArg();
386 }
387
388 const Type *Function::getReturnType() const {
389   return getFunctionType()->getReturnType();
390 }
391
392 void Function::removeFromParent() {
393   getParent()->getFunctionList().remove(this);
394 }
395
396 void Function::eraseFromParent() {
397   getParent()->getFunctionList().erase(this);
398 }
399
400 // dropAllReferences() - This function causes all the subinstructions to "let
401 // go" of all references that they are maintaining.  This allows one to
402 // 'delete' a whole class at a time, even though there may be circular
403 // references... first all references are dropped, and all use counts go to
404 // zero.  Then everything is deleted for real.  Note that no operations are
405 // valid on an object that has "dropped all references", except operator
406 // delete.
407 //
408 void Function::dropAllReferences() {
409   for (iterator I = begin(), E = end(); I != E; ++I)
410     I->dropAllReferences();
411   BasicBlocks.clear();    // Delete all basic blocks...
412 }
413
414 // Maintain the collector name for each function in an on-the-side table. This
415 // saves allocating an additional word in Function for programs which do not use
416 // GC (i.e., most programs) at the cost of increased overhead for clients which
417 // do use GC.
418 static DenseMap<const Function*,PooledStringPtr> *CollectorNames;
419 static StringPool *CollectorNamePool;
420
421 bool Function::hasCollector() const {
422   return CollectorNames && CollectorNames->count(this);
423 }
424
425 const char *Function::getCollector() const {
426   assert(hasCollector() && "Function has no collector");
427   return *(*CollectorNames)[this];
428 }
429
430 void Function::setCollector(const char *Str) {
431   if (!CollectorNamePool)
432     CollectorNamePool = new StringPool();
433   if (!CollectorNames)
434     CollectorNames = new DenseMap<const Function*,PooledStringPtr>();
435   (*CollectorNames)[this] = CollectorNamePool->intern(Str);
436 }
437
438 void Function::clearCollector() {
439   if (CollectorNames) {
440     CollectorNames->erase(this);
441     if (CollectorNames->empty()) {
442       delete CollectorNames;
443       CollectorNames = 0;
444       if (CollectorNamePool->empty()) {
445         delete CollectorNamePool;
446         CollectorNamePool = 0;
447       }
448     }
449   }
450 }
451
452 /// getIntrinsicID - This method returns the ID number of the specified
453 /// function, or Intrinsic::not_intrinsic if the function is not an
454 /// intrinsic, or if the pointer is null.  This value is always defined to be
455 /// zero to allow easy checking for whether a function is intrinsic or not.  The
456 /// particular intrinsic functions which correspond to this value are defined in
457 /// llvm/Intrinsics.h.
458 ///
459 unsigned Function::getIntrinsicID(bool noAssert) const {
460   const ValueName *ValName = this->getValueName();
461   if (!ValName)
462     return 0;
463   unsigned Len = ValName->getKeyLength();
464   const char *Name = ValName->getKeyData();
465   
466   if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
467       || Name[2] != 'v' || Name[3] != 'm')
468     return 0;  // All intrinsics start with 'llvm.'
469
470   assert((Len != 5 || noAssert) && "'llvm.' is an invalid intrinsic name!");
471
472 #define GET_FUNCTION_RECOGNIZER
473 #include "llvm/Intrinsics.gen"
474 #undef GET_FUNCTION_RECOGNIZER
475   assert(noAssert && "Invalid LLVM intrinsic name");
476   return 0;
477 }
478
479 std::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) { 
480   assert(id < num_intrinsics && "Invalid intrinsic ID!");
481   const char * const Table[] = {
482     "not_intrinsic",
483 #define GET_INTRINSIC_NAME_TABLE
484 #include "llvm/Intrinsics.gen"
485 #undef GET_INTRINSIC_NAME_TABLE
486   };
487   if (numTys == 0)
488     return Table[id];
489   std::string Result(Table[id]);
490   for (unsigned i = 0; i < numTys; ++i) 
491     if (Tys[i])
492       Result += "." + MVT::getValueTypeString(MVT::getValueType(Tys[i]));
493   return Result;
494 }
495
496 const FunctionType *Intrinsic::getType(ID id, const Type **Tys, 
497                                        unsigned numTys) {
498   const Type *ResultTy = NULL;
499   std::vector<const Type*> ArgTys;
500   bool IsVarArg = false;
501   
502 #define GET_INTRINSIC_GENERATOR
503 #include "llvm/Intrinsics.gen"
504 #undef GET_INTRINSIC_GENERATOR
505
506   return FunctionType::get(ResultTy, ArgTys, IsVarArg); 
507 }
508
509 const ParamAttrsList *Intrinsic::getParamAttrs(ID id) {
510   static const ParamAttrsList *IntrinsicAttributes[Intrinsic::num_intrinsics];
511
512   if (IntrinsicAttributes[id])
513     return IntrinsicAttributes[id];
514
515   ParamAttrsVector Attrs;
516   uint16_t Attr = ParamAttr::None;
517
518 #define GET_INTRINSIC_ATTRIBUTES
519 #include "llvm/Intrinsics.gen"
520 #undef GET_INTRINSIC_ATTRIBUTES
521
522   // Intrinsics cannot throw exceptions.
523   Attr |= ParamAttr::NoUnwind;
524
525   Attrs.push_back(ParamAttrsWithIndex::get(0, Attr));
526   IntrinsicAttributes[id] = ParamAttrsList::get(Attrs);
527   return IntrinsicAttributes[id];
528 }
529
530 Function *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys, 
531                                     unsigned numTys) {
532   // There can never be multiple globals with the same name of different types,
533   // because intrinsics must be a specific type.
534   Function *F =
535     cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys),
536                                           getType(id, Tys, numTys)));
537   F->setParamAttrs(getParamAttrs(id));
538   return F;
539 }
540
541 Value *IntrinsicInst::StripPointerCasts(Value *Ptr) {
542   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
543     if (CE->getOpcode() == Instruction::BitCast) {
544       if (isa<PointerType>(CE->getOperand(0)->getType()))
545         return StripPointerCasts(CE->getOperand(0));
546     } else if (CE->getOpcode() == Instruction::GetElementPtr) {
547       for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
548         if (!CE->getOperand(i)->isNullValue())
549           return Ptr;
550       return StripPointerCasts(CE->getOperand(0));
551     }
552     return Ptr;
553   }
554
555   if (BitCastInst *CI = dyn_cast<BitCastInst>(Ptr)) {
556     if (isa<PointerType>(CI->getOperand(0)->getType()))
557       return StripPointerCasts(CI->getOperand(0));
558   } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
559     if (GEP->hasAllZeroIndices())
560       return StripPointerCasts(GEP->getOperand(0));
561   }
562   return Ptr;
563 }
564
565 // vim: sw=2 ai