2b83e6b9172c64bafb3f905f7241571bf9b67de7
[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/ParameterAttributes.h"
17 #include "llvm/IntrinsicInst.h"
18 #include "llvm/CodeGen/ValueTypes.h"
19 #include "llvm/Support/LeakDetector.h"
20 #include "llvm/Support/ManagedStatic.h"
21 #include "SymbolTableListTraitsImpl.h"
22 #include "llvm/ADT/StringExtras.h"
23 using namespace llvm;
24
25 BasicBlock *ilist_traits<BasicBlock>::createSentinel() {
26   BasicBlock *Ret = new BasicBlock();
27   // This should not be garbage monitored.
28   LeakDetector::removeGarbageObject(Ret);
29   return Ret;
30 }
31
32 iplist<BasicBlock> &ilist_traits<BasicBlock>::getList(Function *F) {
33   return F->getBasicBlockList();
34 }
35
36 Argument *ilist_traits<Argument>::createSentinel() {
37   Argument *Ret = new Argument(Type::Int32Ty);
38   // This should not be garbage monitored.
39   LeakDetector::removeGarbageObject(Ret);
40   return Ret;
41 }
42
43 iplist<Argument> &ilist_traits<Argument>::getList(Function *F) {
44   return F->getArgumentList();
45 }
46
47 // Explicit instantiations of SymbolTableListTraits since some of the methods
48 // are not in the public header file...
49 template class SymbolTableListTraits<Argument, Function>;
50 template class SymbolTableListTraits<BasicBlock, Function>;
51
52 //===----------------------------------------------------------------------===//
53 // Argument Implementation
54 //===----------------------------------------------------------------------===//
55
56 Argument::Argument(const Type *Ty, const std::string &Name, Function *Par)
57   : Value(Ty, Value::ArgumentVal) {
58   Parent = 0;
59
60   // Make sure that we get added to a function
61   LeakDetector::addGarbageObject(this);
62
63   if (Par)
64     Par->getArgumentList().push_back(this);
65   setName(Name);
66 }
67
68 void Argument::setParent(Function *parent) {
69   if (getParent())
70     LeakDetector::addGarbageObject(this);
71   Parent = parent;
72   if (getParent())
73     LeakDetector::removeGarbageObject(this);
74 }
75
76 //===----------------------------------------------------------------------===//
77 // ParamAttrsList Implementation
78 //===----------------------------------------------------------------------===//
79
80 uint16_t
81 ParamAttrsList::getParamAttrs(uint16_t Index) const {
82   unsigned limit = attrs.size();
83   for (unsigned i = 0; i < limit; ++i)
84     if (attrs[i].index == Index)
85       return attrs[i].attrs;
86   return ParamAttr::None;
87 }
88
89 std::string 
90 ParamAttrsList::getParamAttrsText(uint16_t Attrs) {
91   std::string Result;
92   if (Attrs & ParamAttr::ZExt)
93     Result += "zeroext ";
94   if (Attrs & ParamAttr::SExt)
95     Result += "signext ";
96   if (Attrs & ParamAttr::NoReturn)
97     Result += "noreturn ";
98   if (Attrs & ParamAttr::NoUnwind)
99     Result += "nounwind ";
100   if (Attrs & ParamAttr::InReg)
101     Result += "inreg ";
102   if (Attrs & ParamAttr::NoAlias)
103     Result += "noalias ";
104   if (Attrs & ParamAttr::StructRet)
105     Result += "sret ";  
106   if (Attrs & ParamAttr::ByVal)
107     Result += "byval ";
108   if (Attrs & ParamAttr::Nest)
109     Result += "nest ";
110   if (Attrs & ParamAttr::ReadNone)
111     Result += "readnone ";
112   if (Attrs & ParamAttr::ReadOnly)
113     Result += "readonly ";
114   return Result;
115 }
116
117 /// onlyInformative - Returns whether only informative attributes are set.
118 static inline bool onlyInformative(uint16_t attrs) {
119   return !(attrs & ~ParamAttr::Informative);
120 }
121
122 bool
123 ParamAttrsList::areCompatible(const ParamAttrsList *A, const ParamAttrsList *B){
124   if (A == B)
125     return true;
126   unsigned ASize = A ? A->size() : 0;
127   unsigned BSize = B ? B->size() : 0;
128   unsigned AIndex = 0;
129   unsigned BIndex = 0;
130
131   while (AIndex < ASize && BIndex < BSize) {
132     uint16_t AIdx = A->getParamIndex(AIndex);
133     uint16_t BIdx = B->getParamIndex(BIndex);
134     uint16_t AAttrs = A->getParamAttrsAtIndex(AIndex);
135     uint16_t BAttrs = B->getParamAttrsAtIndex(AIndex);
136
137     if (AIdx < BIdx) {
138       if (!onlyInformative(AAttrs))
139         return false;
140       ++AIndex;
141     } else if (BIdx < AIdx) {
142       if (!onlyInformative(BAttrs))
143         return false;
144       ++BIndex;
145     } else {
146       if (!onlyInformative(AAttrs ^ BAttrs))
147         return false;
148       ++AIndex;
149       ++BIndex;
150     }
151   }
152   for (; AIndex < ASize; ++AIndex)
153     if (!onlyInformative(A->getParamAttrsAtIndex(AIndex)))
154       return false;
155   for (; BIndex < BSize; ++BIndex)
156     if (!onlyInformative(B->getParamAttrsAtIndex(AIndex)))
157       return false;
158   return true;
159 }
160
161 void 
162 ParamAttrsList::Profile(FoldingSetNodeID &ID) const {
163   for (unsigned i = 0; i < attrs.size(); ++i) {
164     unsigned val = attrs[i].attrs << 16 | attrs[i].index;
165     ID.AddInteger(val);
166   }
167 }
168
169 static ManagedStatic<FoldingSet<ParamAttrsList> > ParamAttrsLists;
170
171 ParamAttrsList *
172 ParamAttrsList::get(const ParamAttrsVector &attrVec) {
173   assert(!attrVec.empty() && "Illegal to create empty ParamAttrsList");
174 #ifndef NDEBUG
175   for (unsigned i = 0, e = attrVec.size(); i < e; ++i) {
176     assert(attrVec[i].attrs != ParamAttr::None
177            && "Pointless parameter attribute!");
178     assert((!i || attrVec[i-1].index < attrVec[i].index)
179            && "Misordered ParamAttrsList!");
180   }
181 #endif
182   ParamAttrsList key(attrVec);
183   FoldingSetNodeID ID;
184   key.Profile(ID);
185   void *InsertPos;
186   ParamAttrsList* PAL = ParamAttrsLists->FindNodeOrInsertPos(ID, InsertPos);
187   if (!PAL) {
188     PAL = new ParamAttrsList(attrVec);
189     ParamAttrsLists->InsertNode(PAL, InsertPos);
190   }
191   return PAL;
192 }
193
194 ParamAttrsList::~ParamAttrsList() {
195   ParamAttrsLists->RemoveNode(this);
196 }
197
198 //===----------------------------------------------------------------------===//
199 // Function Implementation
200 //===----------------------------------------------------------------------===//
201
202 Function::Function(const FunctionType *Ty, LinkageTypes Linkage,
203                    const std::string &name, Module *ParentModule)
204   : GlobalValue(PointerType::get(Ty), Value::FunctionVal, 0, 0, Linkage, name) {
205   ParamAttrs = 0;
206   SymTab = new ValueSymbolTable();
207
208   assert((getReturnType()->isFirstClassType() ||getReturnType() == Type::VoidTy)
209          && "LLVM functions cannot return aggregate values!");
210
211   // If the function has arguments, mark them as lazily built.
212   if (Ty->getNumParams())
213     SubclassData = 1;   // Set the "has lazy arguments" bit.
214   
215   // Make sure that we get added to a function
216   LeakDetector::addGarbageObject(this);
217
218   if (ParentModule)
219     ParentModule->getFunctionList().push_back(this);
220 }
221
222 Function::~Function() {
223   dropAllReferences();    // After this it is safe to delete instructions.
224
225   // Delete all of the method arguments and unlink from symbol table...
226   ArgumentList.clear();
227   delete SymTab;
228
229   // Drop our reference to the parameter attributes, if any.
230   if (ParamAttrs)
231     ParamAttrs->dropRef();
232 }
233
234 void Function::BuildLazyArguments() const {
235   // Create the arguments vector, all arguments start out unnamed.
236   const FunctionType *FT = getFunctionType();
237   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
238     assert(FT->getParamType(i) != Type::VoidTy &&
239            "Cannot have void typed arguments!");
240     ArgumentList.push_back(new Argument(FT->getParamType(i)));
241   }
242   
243   // Clear the lazy arguments bit.
244   const_cast<Function*>(this)->SubclassData &= ~1;
245 }
246
247 size_t Function::arg_size() const {
248   return getFunctionType()->getNumParams();
249 }
250 bool Function::arg_empty() const {
251   return getFunctionType()->getNumParams() == 0;
252 }
253
254 void Function::setParent(Module *parent) {
255   if (getParent())
256     LeakDetector::addGarbageObject(this);
257   Parent = parent;
258   if (getParent())
259     LeakDetector::removeGarbageObject(this);
260 }
261
262 void Function::setParamAttrs(ParamAttrsList *attrs) { 
263   if (ParamAttrs)
264     ParamAttrs->dropRef();
265
266   if (attrs)
267     attrs->addRef();
268
269   ParamAttrs = attrs; 
270 }
271
272 const FunctionType *Function::getFunctionType() const {
273   return cast<FunctionType>(getType()->getElementType());
274 }
275
276 bool Function::isVarArg() const {
277   return getFunctionType()->isVarArg();
278 }
279
280 const Type *Function::getReturnType() const {
281   return getFunctionType()->getReturnType();
282 }
283
284 void Function::removeFromParent() {
285   getParent()->getFunctionList().remove(this);
286 }
287
288 void Function::eraseFromParent() {
289   getParent()->getFunctionList().erase(this);
290 }
291
292 // dropAllReferences() - This function causes all the subinstructions to "let
293 // go" of all references that they are maintaining.  This allows one to
294 // 'delete' a whole class at a time, even though there may be circular
295 // references... first all references are dropped, and all use counts go to
296 // zero.  Then everything is deleted for real.  Note that no operations are
297 // valid on an object that has "dropped all references", except operator
298 // delete.
299 //
300 void Function::dropAllReferences() {
301   for (iterator I = begin(), E = end(); I != E; ++I)
302     I->dropAllReferences();
303   BasicBlocks.clear();    // Delete all basic blocks...
304 }
305
306 /// getIntrinsicID - This method returns the ID number of the specified
307 /// function, or Intrinsic::not_intrinsic if the function is not an
308 /// intrinsic, or if the pointer is null.  This value is always defined to be
309 /// zero to allow easy checking for whether a function is intrinsic or not.  The
310 /// particular intrinsic functions which correspond to this value are defined in
311 /// llvm/Intrinsics.h.
312 ///
313 unsigned Function::getIntrinsicID(bool noAssert) const {
314   const ValueName *ValName = this->getValueName();
315   if (!ValName)
316     return 0;
317   unsigned Len = ValName->getKeyLength();
318   const char *Name = ValName->getKeyData();
319   
320   if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
321       || Name[2] != 'v' || Name[3] != 'm')
322     return 0;  // All intrinsics start with 'llvm.'
323
324   assert((Len != 5 || noAssert) && "'llvm.' is an invalid intrinsic name!");
325
326 #define GET_FUNCTION_RECOGNIZER
327 #include "llvm/Intrinsics.gen"
328 #undef GET_FUNCTION_RECOGNIZER
329   assert(noAssert && "Invalid LLVM intrinsic name");
330   return 0;
331 }
332
333 std::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) { 
334   assert(id < num_intrinsics && "Invalid intrinsic ID!");
335   const char * const Table[] = {
336     "not_intrinsic",
337 #define GET_INTRINSIC_NAME_TABLE
338 #include "llvm/Intrinsics.gen"
339 #undef GET_INTRINSIC_NAME_TABLE
340   };
341   if (numTys == 0)
342     return Table[id];
343   std::string Result(Table[id]);
344   for (unsigned i = 0; i < numTys; ++i) 
345     if (Tys[i])
346       Result += "." + MVT::getValueTypeString(MVT::getValueType(Tys[i]));
347   return Result;
348 }
349
350 const FunctionType *Intrinsic::getType(ID id, const Type **Tys, 
351                                        unsigned numTys) {
352   const Type *ResultTy = NULL;
353   std::vector<const Type*> ArgTys;
354   bool IsVarArg = false;
355   
356 #define GET_INTRINSIC_GENERATOR
357 #include "llvm/Intrinsics.gen"
358 #undef GET_INTRINSIC_GENERATOR
359
360   return FunctionType::get(ResultTy, ArgTys, IsVarArg); 
361 }
362
363 Function *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys, 
364                                     unsigned numTys) {
365 // There can never be multiple globals with the same name of different types,
366 // because intrinsics must be a specific type.
367   return cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys), 
368                                                getType(id, Tys, numTys)));
369 }
370
371 Value *IntrinsicInst::StripPointerCasts(Value *Ptr) {
372   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
373     if (CE->getOpcode() == Instruction::BitCast) {
374       if (isa<PointerType>(CE->getOperand(0)->getType()))
375         return StripPointerCasts(CE->getOperand(0));
376     } else if (CE->getOpcode() == Instruction::GetElementPtr) {
377       for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
378         if (!CE->getOperand(i)->isNullValue())
379           return Ptr;
380       return StripPointerCasts(CE->getOperand(0));
381     }
382     return Ptr;
383   }
384
385   if (BitCastInst *CI = dyn_cast<BitCastInst>(Ptr)) {
386     if (isa<PointerType>(CI->getOperand(0)->getType()))
387       return StripPointerCasts(CI->getOperand(0));
388   } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
389     if (GEP->hasAllZeroIndices())
390       return StripPointerCasts(GEP->getOperand(0));
391   }
392   return Ptr;
393 }
394
395 // vim: sw=2 ai