merge several fields in GlobalValue to use the same word, move CallingConv
[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/Support/LeakDetector.h"
19 #include "SymbolTableListTraitsImpl.h"
20 #include "llvm/ADT/StringExtras.h"
21 using namespace llvm;
22
23 BasicBlock *ilist_traits<BasicBlock>::createSentinel() {
24   BasicBlock *Ret = new BasicBlock();
25   // This should not be garbage monitored.
26   LeakDetector::removeGarbageObject(Ret);
27   return Ret;
28 }
29
30 iplist<BasicBlock> &ilist_traits<BasicBlock>::getList(Function *F) {
31   return F->getBasicBlockList();
32 }
33
34 Argument *ilist_traits<Argument>::createSentinel() {
35   Argument *Ret = new Argument(Type::Int32Ty);
36   // This should not be garbage monitored.
37   LeakDetector::removeGarbageObject(Ret);
38   return Ret;
39 }
40
41 iplist<Argument> &ilist_traits<Argument>::getList(Function *F) {
42   return F->getArgumentList();
43 }
44
45 // Explicit instantiations of SymbolTableListTraits since some of the methods
46 // are not in the public header file...
47 template class SymbolTableListTraits<Argument, Function>;
48 template class SymbolTableListTraits<BasicBlock, Function>;
49
50 //===----------------------------------------------------------------------===//
51 // Argument Implementation
52 //===----------------------------------------------------------------------===//
53
54 Argument::Argument(const Type *Ty, const std::string &Name, Function *Par)
55   : Value(Ty, Value::ArgumentVal) {
56   Parent = 0;
57
58   // Make sure that we get added to a function
59   LeakDetector::addGarbageObject(this);
60
61   if (Par)
62     Par->getArgumentList().push_back(this);
63   setName(Name);
64 }
65
66 void Argument::setParent(Function *parent) {
67   if (getParent())
68     LeakDetector::addGarbageObject(this);
69   Parent = parent;
70   if (getParent())
71     LeakDetector::removeGarbageObject(this);
72 }
73
74 //===----------------------------------------------------------------------===//
75 // ParamAttrsList Implementation
76 //===----------------------------------------------------------------------===//
77
78 uint16_t
79 ParamAttrsList::getParamAttrs(uint16_t Index) const {
80   unsigned limit = attrs.size();
81   for (unsigned i = 0; i < limit; ++i)
82     if (attrs[i].index == Index)
83       return attrs[i].attrs;
84   return ParamAttr::None;
85 }
86
87
88 std::string 
89 ParamAttrsList::getParamAttrsText(uint16_t Attrs) {
90   std::string Result;
91   if (Attrs & ParamAttr::ZExt)
92     Result += "zext ";
93   if (Attrs & ParamAttr::SExt)
94     Result += "sext ";
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::StructRet)
102     Result += "sret ";  
103   return Result;
104 }
105
106 void
107 ParamAttrsList::addAttributes(uint16_t Index, uint16_t Attrs) {
108   // First, try to replace an existing one
109   for (unsigned i = 0; i < attrs.size(); ++i)
110     if (attrs[i].index == Index) {
111       attrs[i].attrs |= Attrs;
112       return;
113     }
114
115   // If not found, add a new one
116   ParamAttrsWithIndex Val;
117   Val.attrs = Attrs;
118   Val.index = Index;
119   attrs.push_back(Val);
120 }
121
122 void
123 ParamAttrsList::removeAttributes(uint16_t Index, uint16_t Attrs) {
124   // Find the index from which to remove the attributes
125   for (unsigned i = 0; i < attrs.size(); ++i)
126     if (attrs[i].index == Index) {
127       attrs[i].attrs &= ~Attrs;
128       if (attrs[i].attrs == ParamAttr::None)
129         attrs.erase(&attrs[i]);
130       return;
131     }
132
133   // The index wasn't found above
134   assert(0 && "Index not found for removeAttributes");
135 }
136
137 //===----------------------------------------------------------------------===//
138 // Function Implementation
139 //===----------------------------------------------------------------------===//
140
141 Function::Function(const FunctionType *Ty, LinkageTypes Linkage,
142                    const std::string &name, Module *ParentModule)
143   : GlobalValue(PointerType::get(Ty), Value::FunctionVal, 0, 0, Linkage, name) {
144   ParamAttrs = 0;
145   SymTab = new ValueSymbolTable();
146
147   assert((getReturnType()->isFirstClassType() ||getReturnType() == Type::VoidTy)
148          && "LLVM functions cannot return aggregate values!");
149
150   // Create the arguments vector, all arguments start out unnamed.
151   for (unsigned i = 0, e = Ty->getNumParams(); i != e; ++i) {
152     assert(Ty->getParamType(i) != Type::VoidTy &&
153            "Cannot have void typed arguments!");
154     ArgumentList.push_back(new Argument(Ty->getParamType(i)));
155   }
156
157   // Make sure that we get added to a function
158   LeakDetector::addGarbageObject(this);
159
160   if (ParentModule)
161     ParentModule->getFunctionList().push_back(this);
162 }
163
164 Function::~Function() {
165   dropAllReferences();    // After this it is safe to delete instructions.
166
167   // Delete all of the method arguments and unlink from symbol table...
168   ArgumentList.clear();
169   delete SymTab;
170 }
171
172 void Function::setParent(Module *parent) {
173   if (getParent())
174     LeakDetector::addGarbageObject(this);
175   Parent = parent;
176   if (getParent())
177     LeakDetector::removeGarbageObject(this);
178 }
179
180 const FunctionType *Function::getFunctionType() const {
181   return cast<FunctionType>(getType()->getElementType());
182 }
183
184 bool Function::isVarArg() const {
185   return getFunctionType()->isVarArg();
186 }
187
188 const Type *Function::getReturnType() const {
189   return getFunctionType()->getReturnType();
190 }
191
192 void Function::removeFromParent() {
193   getParent()->getFunctionList().remove(this);
194 }
195
196 void Function::eraseFromParent() {
197   getParent()->getFunctionList().erase(this);
198 }
199
200 // dropAllReferences() - This function causes all the subinstructions to "let
201 // go" of all references that they are maintaining.  This allows one to
202 // 'delete' a whole class at a time, even though there may be circular
203 // references... first all references are dropped, and all use counts go to
204 // zero.  Then everything is deleted for real.  Note that no operations are
205 // valid on an object that has "dropped all references", except operator
206 // delete.
207 //
208 void Function::dropAllReferences() {
209   for (iterator I = begin(), E = end(); I != E; ++I)
210     I->dropAllReferences();
211   BasicBlocks.clear();    // Delete all basic blocks...
212 }
213
214 /// getIntrinsicID - This method returns the ID number of the specified
215 /// function, or Intrinsic::not_intrinsic if the function is not an
216 /// intrinsic, or if the pointer is null.  This value is always defined to be
217 /// zero to allow easy checking for whether a function is intrinsic or not.  The
218 /// particular intrinsic functions which correspond to this value are defined in
219 /// llvm/Intrinsics.h.
220 ///
221 unsigned Function::getIntrinsicID(bool noAssert) const {
222   const ValueName *ValName = this->getValueName();
223   if (!ValName)
224     return 0;
225   unsigned Len = ValName->getKeyLength();
226   const char *Name = ValName->getKeyData();
227   
228   if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
229       || Name[2] != 'v' || Name[3] != 'm')
230     return 0;  // All intrinsics start with 'llvm.'
231
232   assert((Len != 5 || noAssert) && "'llvm.' is an invalid intrinsic name!");
233
234 #define GET_FUNCTION_RECOGNIZER
235 #include "llvm/Intrinsics.gen"
236 #undef GET_FUNCTION_RECOGNIZER
237   assert(noAssert && "Invalid LLVM intrinsic name");
238   return 0;
239 }
240
241 std::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) { 
242   assert(id < num_intrinsics && "Invalid intrinsic ID!");
243   const char * const Table[] = {
244     "not_intrinsic",
245 #define GET_INTRINSIC_NAME_TABLE
246 #include "llvm/Intrinsics.gen"
247 #undef GET_INTRINSIC_NAME_TABLE
248   };
249   if (numTys == 0)
250     return Table[id];
251   std::string Result(Table[id]);
252   for (unsigned i = 0; i < numTys; ++i) 
253     if (Tys[i])
254       Result += "." + Tys[i]->getDescription();
255   return Result;
256 }
257
258 const FunctionType *Intrinsic::getType(ID id, const Type **Tys, 
259                                        uint32_t numTys) {
260   const Type *ResultTy = NULL;
261   std::vector<const Type*> ArgTys;
262   bool IsVarArg = false;
263   
264 #define GET_INTRINSIC_GENERATOR
265 #include "llvm/Intrinsics.gen"
266 #undef GET_INTRINSIC_GENERATOR
267
268   return FunctionType::get(ResultTy, ArgTys, IsVarArg); 
269 }
270
271 Function *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys, 
272                                     unsigned numTys) {
273 // There can never be multiple globals with the same name of different types,
274 // because intrinsics must be a specific type.
275   return cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys), 
276                                                getType(id, Tys, numTys)));
277 }
278
279 Value *IntrinsicInst::StripPointerCasts(Value *Ptr) {
280   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
281     if (CE->getOpcode() == Instruction::BitCast) {
282       if (isa<PointerType>(CE->getOperand(0)->getType()))
283         return StripPointerCasts(CE->getOperand(0));
284     } else if (CE->getOpcode() == Instruction::GetElementPtr) {
285       for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
286         if (!CE->getOperand(i)->isNullValue())
287           return Ptr;
288       return StripPointerCasts(CE->getOperand(0));
289     }
290     return Ptr;
291   }
292
293   if (BitCastInst *CI = dyn_cast<BitCastInst>(Ptr)) {
294     if (isa<PointerType>(CI->getOperand(0)->getType()))
295       return StripPointerCasts(CI->getOperand(0));
296   } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
297     for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
298       if (!isa<Constant>(GEP->getOperand(i)) ||
299           !cast<Constant>(GEP->getOperand(i))->isNullValue())
300         return Ptr;
301     return StripPointerCasts(GEP->getOperand(0));
302   }
303   return Ptr;
304 }
305
306 // vim: sw=2 ai