Rename the 'const' parameter attribute to 'readnone',
[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
90 std::string 
91 ParamAttrsList::getParamAttrsText(uint16_t Attrs) {
92   std::string Result;
93   if (Attrs & ParamAttr::ZExt)
94     Result += "zeroext ";
95   if (Attrs & ParamAttr::SExt)
96     Result += "signext ";
97   if (Attrs & ParamAttr::NoReturn)
98     Result += "noreturn ";
99   if (Attrs & ParamAttr::NoUnwind)
100     Result += "nounwind ";
101   if (Attrs & ParamAttr::InReg)
102     Result += "inreg ";
103   if (Attrs & ParamAttr::NoAlias)
104     Result += "noalias ";
105   if (Attrs & ParamAttr::StructRet)
106     Result += "sret ";  
107   if (Attrs & ParamAttr::ByVal)
108     Result += "byval ";
109   if (Attrs & ParamAttr::Nest)
110     Result += "nest ";
111   if (Attrs & ParamAttr::ReadNone)
112     Result += "readnone ";
113   if (Attrs & ParamAttr::ReadOnly)
114     Result += "readonly ";
115   return Result;
116 }
117
118 void 
119 ParamAttrsList::Profile(FoldingSetNodeID &ID) const {
120   for (unsigned i = 0; i < attrs.size(); ++i) {
121     unsigned val = attrs[i].attrs << 16 | attrs[i].index;
122     ID.AddInteger(val);
123   }
124 }
125
126 static ManagedStatic<FoldingSet<ParamAttrsList> > ParamAttrsLists;
127
128 ParamAttrsList *
129 ParamAttrsList::get(const ParamAttrsVector &attrVec) {
130   assert(!attrVec.empty() && "Illegal to create empty ParamAttrsList");
131 #ifndef NDEBUG
132   for (unsigned i = 0, e = attrVec.size(); i < e; ++i) {
133     assert(attrVec[i].attrs != ParamAttr::None
134            && "Pointless parameter attribute!");
135     assert((!i || attrVec[i-1].index < attrVec[i].index)
136            && "Misordered ParamAttrsList!");
137   }
138 #endif
139   ParamAttrsList key(attrVec);
140   FoldingSetNodeID ID;
141   key.Profile(ID);
142   void *InsertPos;
143   ParamAttrsList* PAL = ParamAttrsLists->FindNodeOrInsertPos(ID, InsertPos);
144   if (!PAL) {
145     PAL = new ParamAttrsList(attrVec);
146     ParamAttrsLists->InsertNode(PAL, InsertPos);
147   }
148   return PAL;
149 }
150
151 ParamAttrsList::~ParamAttrsList() {
152   ParamAttrsLists->RemoveNode(this);
153 }
154
155 //===----------------------------------------------------------------------===//
156 // Function Implementation
157 //===----------------------------------------------------------------------===//
158
159 Function::Function(const FunctionType *Ty, LinkageTypes Linkage,
160                    const std::string &name, Module *ParentModule)
161   : GlobalValue(PointerType::get(Ty), Value::FunctionVal, 0, 0, Linkage, name) {
162   ParamAttrs = 0;
163   SymTab = new ValueSymbolTable();
164
165   assert((getReturnType()->isFirstClassType() ||getReturnType() == Type::VoidTy)
166          && "LLVM functions cannot return aggregate values!");
167
168   // If the function has arguments, mark them as lazily built.
169   if (Ty->getNumParams())
170     SubclassData = 1;   // Set the "has lazy arguments" bit.
171   
172   // Make sure that we get added to a function
173   LeakDetector::addGarbageObject(this);
174
175   if (ParentModule)
176     ParentModule->getFunctionList().push_back(this);
177 }
178
179 Function::~Function() {
180   dropAllReferences();    // After this it is safe to delete instructions.
181
182   // Delete all of the method arguments and unlink from symbol table...
183   ArgumentList.clear();
184   delete SymTab;
185
186   // Drop our reference to the parameter attributes, if any.
187   if (ParamAttrs)
188     ParamAttrs->dropRef();
189 }
190
191 void Function::BuildLazyArguments() const {
192   // Create the arguments vector, all arguments start out unnamed.
193   const FunctionType *FT = getFunctionType();
194   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
195     assert(FT->getParamType(i) != Type::VoidTy &&
196            "Cannot have void typed arguments!");
197     ArgumentList.push_back(new Argument(FT->getParamType(i)));
198   }
199   
200   // Clear the lazy arguments bit.
201   const_cast<Function*>(this)->SubclassData &= ~1;
202 }
203
204 size_t Function::arg_size() const {
205   return getFunctionType()->getNumParams();
206 }
207 bool Function::arg_empty() const {
208   return getFunctionType()->getNumParams() == 0;
209 }
210
211 void Function::setParent(Module *parent) {
212   if (getParent())
213     LeakDetector::addGarbageObject(this);
214   Parent = parent;
215   if (getParent())
216     LeakDetector::removeGarbageObject(this);
217 }
218
219 void Function::setParamAttrs(ParamAttrsList *attrs) { 
220   if (ParamAttrs)
221     ParamAttrs->dropRef();
222
223   if (attrs)
224     attrs->addRef();
225
226   ParamAttrs = attrs; 
227 }
228
229 const FunctionType *Function::getFunctionType() const {
230   return cast<FunctionType>(getType()->getElementType());
231 }
232
233 bool Function::isVarArg() const {
234   return getFunctionType()->isVarArg();
235 }
236
237 const Type *Function::getReturnType() const {
238   return getFunctionType()->getReturnType();
239 }
240
241 void Function::removeFromParent() {
242   getParent()->getFunctionList().remove(this);
243 }
244
245 void Function::eraseFromParent() {
246   getParent()->getFunctionList().erase(this);
247 }
248
249 // dropAllReferences() - This function causes all the subinstructions to "let
250 // go" of all references that they are maintaining.  This allows one to
251 // 'delete' a whole class at a time, even though there may be circular
252 // references... first all references are dropped, and all use counts go to
253 // zero.  Then everything is deleted for real.  Note that no operations are
254 // valid on an object that has "dropped all references", except operator
255 // delete.
256 //
257 void Function::dropAllReferences() {
258   for (iterator I = begin(), E = end(); I != E; ++I)
259     I->dropAllReferences();
260   BasicBlocks.clear();    // Delete all basic blocks...
261 }
262
263 /// getIntrinsicID - This method returns the ID number of the specified
264 /// function, or Intrinsic::not_intrinsic if the function is not an
265 /// intrinsic, or if the pointer is null.  This value is always defined to be
266 /// zero to allow easy checking for whether a function is intrinsic or not.  The
267 /// particular intrinsic functions which correspond to this value are defined in
268 /// llvm/Intrinsics.h.
269 ///
270 unsigned Function::getIntrinsicID(bool noAssert) const {
271   const ValueName *ValName = this->getValueName();
272   if (!ValName)
273     return 0;
274   unsigned Len = ValName->getKeyLength();
275   const char *Name = ValName->getKeyData();
276   
277   if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
278       || Name[2] != 'v' || Name[3] != 'm')
279     return 0;  // All intrinsics start with 'llvm.'
280
281   assert((Len != 5 || noAssert) && "'llvm.' is an invalid intrinsic name!");
282
283 #define GET_FUNCTION_RECOGNIZER
284 #include "llvm/Intrinsics.gen"
285 #undef GET_FUNCTION_RECOGNIZER
286   assert(noAssert && "Invalid LLVM intrinsic name");
287   return 0;
288 }
289
290 std::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) { 
291   assert(id < num_intrinsics && "Invalid intrinsic ID!");
292   const char * const Table[] = {
293     "not_intrinsic",
294 #define GET_INTRINSIC_NAME_TABLE
295 #include "llvm/Intrinsics.gen"
296 #undef GET_INTRINSIC_NAME_TABLE
297   };
298   if (numTys == 0)
299     return Table[id];
300   std::string Result(Table[id]);
301   for (unsigned i = 0; i < numTys; ++i) 
302     if (Tys[i])
303       Result += "." + MVT::getValueTypeString(MVT::getValueType(Tys[i]));
304   return Result;
305 }
306
307 const FunctionType *Intrinsic::getType(ID id, const Type **Tys, 
308                                        unsigned numTys) {
309   const Type *ResultTy = NULL;
310   std::vector<const Type*> ArgTys;
311   bool IsVarArg = false;
312   
313 #define GET_INTRINSIC_GENERATOR
314 #include "llvm/Intrinsics.gen"
315 #undef GET_INTRINSIC_GENERATOR
316
317   return FunctionType::get(ResultTy, ArgTys, IsVarArg); 
318 }
319
320 Function *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys, 
321                                     unsigned numTys) {
322 // There can never be multiple globals with the same name of different types,
323 // because intrinsics must be a specific type.
324   return cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys), 
325                                                getType(id, Tys, numTys)));
326 }
327
328 Value *IntrinsicInst::StripPointerCasts(Value *Ptr) {
329   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
330     if (CE->getOpcode() == Instruction::BitCast) {
331       if (isa<PointerType>(CE->getOperand(0)->getType()))
332         return StripPointerCasts(CE->getOperand(0));
333     } else if (CE->getOpcode() == Instruction::GetElementPtr) {
334       for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
335         if (!CE->getOperand(i)->isNullValue())
336           return Ptr;
337       return StripPointerCasts(CE->getOperand(0));
338     }
339     return Ptr;
340   }
341
342   if (BitCastInst *CI = dyn_cast<BitCastInst>(Ptr)) {
343     if (isa<PointerType>(CI->getOperand(0)->getType()))
344       return StripPointerCasts(CI->getOperand(0));
345   } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
346     if (GEP->hasAllZeroIndices())
347       return StripPointerCasts(GEP->getOperand(0));
348   }
349   return Ptr;
350 }
351
352 // vim: sw=2 ai