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