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