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