Add a convenience method for modifying parameter
[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 was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 "SymbolTableListTraitsImpl.h"
21 #include "llvm/ADT/StringExtras.h"
22 using namespace llvm;
23
24 BasicBlock *ilist_traits<BasicBlock>::createSentinel() {
25   BasicBlock *Ret = new BasicBlock();
26   // This should not be garbage monitored.
27   LeakDetector::removeGarbageObject(Ret);
28   return Ret;
29 }
30
31 iplist<BasicBlock> &ilist_traits<BasicBlock>::getList(Function *F) {
32   return F->getBasicBlockList();
33 }
34
35 Argument *ilist_traits<Argument>::createSentinel() {
36   Argument *Ret = new Argument(Type::Int32Ty);
37   // This should not be garbage monitored.
38   LeakDetector::removeGarbageObject(Ret);
39   return Ret;
40 }
41
42 iplist<Argument> &ilist_traits<Argument>::getList(Function *F) {
43   return F->getArgumentList();
44 }
45
46 // Explicit instantiations of SymbolTableListTraits since some of the methods
47 // are not in the public header file...
48 template class SymbolTableListTraits<Argument, Function>;
49 template class SymbolTableListTraits<BasicBlock, Function>;
50
51 //===----------------------------------------------------------------------===//
52 // Argument Implementation
53 //===----------------------------------------------------------------------===//
54
55 Argument::Argument(const Type *Ty, const std::string &Name, Function *Par)
56   : Value(Ty, Value::ArgumentVal) {
57   Parent = 0;
58
59   // Make sure that we get added to a function
60   LeakDetector::addGarbageObject(this);
61
62   if (Par)
63     Par->getArgumentList().push_back(this);
64   setName(Name);
65 }
66
67 void Argument::setParent(Function *parent) {
68   if (getParent())
69     LeakDetector::addGarbageObject(this);
70   Parent = parent;
71   if (getParent())
72     LeakDetector::removeGarbageObject(this);
73 }
74
75 //===----------------------------------------------------------------------===//
76 // ParamAttrsList Implementation
77 //===----------------------------------------------------------------------===//
78
79 uint16_t
80 ParamAttrsList::getParamAttrs(uint16_t Index) const {
81   unsigned limit = attrs.size();
82   for (unsigned i = 0; i < limit; ++i)
83     if (attrs[i].index == Index)
84       return attrs[i].attrs;
85   return ParamAttr::None;
86 }
87
88 std::string 
89 ParamAttrsList::getParamAttrsText(uint16_t Attrs) {
90   std::string Result;
91   if (Attrs & ParamAttr::ZExt)
92     Result += "zeroext ";
93   if (Attrs & ParamAttr::SExt)
94     Result += "signext ";
95   if (Attrs & ParamAttr::NoReturn)
96     Result += "noreturn ";
97   if (Attrs & ParamAttr::NoUnwind)
98     Result += "nounwind ";
99   if (Attrs & ParamAttr::InReg)
100     Result += "inreg ";
101   if (Attrs & ParamAttr::NoAlias)
102     Result += "noalias ";
103   if (Attrs & ParamAttr::StructRet)
104     Result += "sret ";  
105   if (Attrs & ParamAttr::ByVal)
106     Result += "byval ";
107   if (Attrs & ParamAttr::Nest)
108     Result += "nest ";
109   if (Attrs & ParamAttr::ReadNone)
110     Result += "readnone ";
111   if (Attrs & ParamAttr::ReadOnly)
112     Result += "readonly ";
113   return Result;
114 }
115
116 /// onlyInformative - Returns whether only informative attributes are set.
117 static inline bool onlyInformative(uint16_t attrs) {
118   return !(attrs & ~ParamAttr::Informative);
119 }
120
121 bool
122 ParamAttrsList::areCompatible(const ParamAttrsList *A, const ParamAttrsList *B){
123   if (A == B)
124     return true;
125   unsigned ASize = A ? A->size() : 0;
126   unsigned BSize = B ? B->size() : 0;
127   unsigned AIndex = 0;
128   unsigned BIndex = 0;
129
130   while (AIndex < ASize && BIndex < BSize) {
131     uint16_t AIdx = A->getParamIndex(AIndex);
132     uint16_t BIdx = B->getParamIndex(BIndex);
133     uint16_t AAttrs = A->getParamAttrsAtIndex(AIndex);
134     uint16_t BAttrs = B->getParamAttrsAtIndex(AIndex);
135
136     if (AIdx < BIdx) {
137       if (!onlyInformative(AAttrs))
138         return false;
139       ++AIndex;
140     } else if (BIdx < AIdx) {
141       if (!onlyInformative(BAttrs))
142         return false;
143       ++BIndex;
144     } else {
145       if (!onlyInformative(AAttrs ^ BAttrs))
146         return false;
147       ++AIndex;
148       ++BIndex;
149     }
150   }
151   for (; AIndex < ASize; ++AIndex)
152     if (!onlyInformative(A->getParamAttrsAtIndex(AIndex)))
153       return false;
154   for (; BIndex < BSize; ++BIndex)
155     if (!onlyInformative(B->getParamAttrsAtIndex(AIndex)))
156       return false;
157   return true;
158 }
159
160 void 
161 ParamAttrsList::Profile(FoldingSetNodeID &ID) const {
162   for (unsigned i = 0; i < attrs.size(); ++i) {
163     uint32_t val = uint32_t(attrs[i].attrs) << 16 | attrs[i].index;
164     ID.AddInteger(val);
165   }
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 ParamAttrsList::~ParamAttrsList() {
262   ParamAttrsLists->RemoveNode(this);
263 }
264
265 //===----------------------------------------------------------------------===//
266 // Function Implementation
267 //===----------------------------------------------------------------------===//
268
269 Function::Function(const FunctionType *Ty, LinkageTypes Linkage,
270                    const std::string &name, Module *ParentModule)
271   : GlobalValue(PointerType::get(Ty), Value::FunctionVal, 0, 0, Linkage, name),
272     ParamAttrs(0) {
273   SymTab = new ValueSymbolTable();
274
275   assert((getReturnType()->isFirstClassType() ||getReturnType() == Type::VoidTy)
276          && "LLVM functions cannot return aggregate values!");
277
278   // If the function has arguments, mark them as lazily built.
279   if (Ty->getNumParams())
280     SubclassData = 1;   // Set the "has lazy arguments" bit.
281   
282   // Make sure that we get added to a function
283   LeakDetector::addGarbageObject(this);
284
285   if (ParentModule)
286     ParentModule->getFunctionList().push_back(this);
287 }
288
289 Function::~Function() {
290   dropAllReferences();    // After this it is safe to delete instructions.
291
292   // Delete all of the method arguments and unlink from symbol table...
293   ArgumentList.clear();
294   delete SymTab;
295
296   // Drop our reference to the parameter attributes, if any.
297   if (ParamAttrs)
298     ParamAttrs->dropRef();
299 }
300
301 void Function::BuildLazyArguments() const {
302   // Create the arguments vector, all arguments start out unnamed.
303   const FunctionType *FT = getFunctionType();
304   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
305     assert(FT->getParamType(i) != Type::VoidTy &&
306            "Cannot have void typed arguments!");
307     ArgumentList.push_back(new Argument(FT->getParamType(i)));
308   }
309   
310   // Clear the lazy arguments bit.
311   const_cast<Function*>(this)->SubclassData &= ~1;
312 }
313
314 size_t Function::arg_size() const {
315   return getFunctionType()->getNumParams();
316 }
317 bool Function::arg_empty() const {
318   return getFunctionType()->getNumParams() == 0;
319 }
320
321 void Function::setParent(Module *parent) {
322   if (getParent())
323     LeakDetector::addGarbageObject(this);
324   Parent = parent;
325   if (getParent())
326     LeakDetector::removeGarbageObject(this);
327 }
328
329 void Function::setParamAttrs(const ParamAttrsList *attrs) {
330   // Avoid deleting the ParamAttrsList if they are setting the
331   // attributes to the same list.
332   if (ParamAttrs == attrs)
333     return;
334
335   // Drop reference on the old ParamAttrsList
336   if (ParamAttrs)
337     ParamAttrs->dropRef();
338
339   // Add reference to the new ParamAttrsList
340   if (attrs)
341     attrs->addRef();
342
343   // Set the new ParamAttrsList.
344   ParamAttrs = attrs; 
345 }
346
347 const FunctionType *Function::getFunctionType() const {
348   return cast<FunctionType>(getType()->getElementType());
349 }
350
351 bool Function::isVarArg() const {
352   return getFunctionType()->isVarArg();
353 }
354
355 const Type *Function::getReturnType() const {
356   return getFunctionType()->getReturnType();
357 }
358
359 void Function::removeFromParent() {
360   getParent()->getFunctionList().remove(this);
361 }
362
363 void Function::eraseFromParent() {
364   getParent()->getFunctionList().erase(this);
365 }
366
367 // dropAllReferences() - This function causes all the subinstructions to "let
368 // go" of all references that they are maintaining.  This allows one to
369 // 'delete' a whole class at a time, even though there may be circular
370 // references... first all references are dropped, and all use counts go to
371 // zero.  Then everything is deleted for real.  Note that no operations are
372 // valid on an object that has "dropped all references", except operator
373 // delete.
374 //
375 void Function::dropAllReferences() {
376   for (iterator I = begin(), E = end(); I != E; ++I)
377     I->dropAllReferences();
378   BasicBlocks.clear();    // Delete all basic blocks...
379 }
380
381 /// getIntrinsicID - This method returns the ID number of the specified
382 /// function, or Intrinsic::not_intrinsic if the function is not an
383 /// intrinsic, or if the pointer is null.  This value is always defined to be
384 /// zero to allow easy checking for whether a function is intrinsic or not.  The
385 /// particular intrinsic functions which correspond to this value are defined in
386 /// llvm/Intrinsics.h.
387 ///
388 unsigned Function::getIntrinsicID(bool noAssert) const {
389   const ValueName *ValName = this->getValueName();
390   if (!ValName)
391     return 0;
392   unsigned Len = ValName->getKeyLength();
393   const char *Name = ValName->getKeyData();
394   
395   if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
396       || Name[2] != 'v' || Name[3] != 'm')
397     return 0;  // All intrinsics start with 'llvm.'
398
399   assert((Len != 5 || noAssert) && "'llvm.' is an invalid intrinsic name!");
400
401 #define GET_FUNCTION_RECOGNIZER
402 #include "llvm/Intrinsics.gen"
403 #undef GET_FUNCTION_RECOGNIZER
404   assert(noAssert && "Invalid LLVM intrinsic name");
405   return 0;
406 }
407
408 std::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) { 
409   assert(id < num_intrinsics && "Invalid intrinsic ID!");
410   const char * const Table[] = {
411     "not_intrinsic",
412 #define GET_INTRINSIC_NAME_TABLE
413 #include "llvm/Intrinsics.gen"
414 #undef GET_INTRINSIC_NAME_TABLE
415   };
416   if (numTys == 0)
417     return Table[id];
418   std::string Result(Table[id]);
419   for (unsigned i = 0; i < numTys; ++i) 
420     if (Tys[i])
421       Result += "." + MVT::getValueTypeString(MVT::getValueType(Tys[i]));
422   return Result;
423 }
424
425 const FunctionType *Intrinsic::getType(ID id, const Type **Tys, 
426                                        unsigned numTys) {
427   const Type *ResultTy = NULL;
428   std::vector<const Type*> ArgTys;
429   bool IsVarArg = false;
430   
431 #define GET_INTRINSIC_GENERATOR
432 #include "llvm/Intrinsics.gen"
433 #undef GET_INTRINSIC_GENERATOR
434
435   return FunctionType::get(ResultTy, ArgTys, IsVarArg); 
436 }
437
438 Function *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys, 
439                                     unsigned numTys) {
440 // There can never be multiple globals with the same name of different types,
441 // because intrinsics must be a specific type.
442   return cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys), 
443                                                getType(id, Tys, numTys)));
444 }
445
446 Value *IntrinsicInst::StripPointerCasts(Value *Ptr) {
447   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
448     if (CE->getOpcode() == Instruction::BitCast) {
449       if (isa<PointerType>(CE->getOperand(0)->getType()))
450         return StripPointerCasts(CE->getOperand(0));
451     } else if (CE->getOpcode() == Instruction::GetElementPtr) {
452       for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
453         if (!CE->getOperand(i)->isNullValue())
454           return Ptr;
455       return StripPointerCasts(CE->getOperand(0));
456     }
457     return Ptr;
458   }
459
460   if (BitCastInst *CI = dyn_cast<BitCastInst>(Ptr)) {
461     if (isa<PointerType>(CI->getOperand(0)->getType()))
462       return StripPointerCasts(CI->getOperand(0));
463   } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
464     if (GEP->hasAllZeroIndices())
465       return StripPointerCasts(GEP->getOperand(0));
466   }
467   return Ptr;
468 }
469
470 // vim: sw=2 ai