s/isReturnStruct()/hasStructRetAttr()/g
[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/ParamAttrsList.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 /// getArgNo - Return the index of this formal argument in its containing
79 /// function.  For example in "void foo(int a, float b)" a is 0 and b is 1. 
80 unsigned Argument::getArgNo() const {
81   const Function *F = getParent();
82   assert(F && "Argument is not in a function");
83   
84   Function::const_arg_iterator AI = F->arg_begin();
85   unsigned ArgIdx = 0;
86   for (; &*AI != this; ++AI)
87     ++ArgIdx;
88
89   return ArgIdx;
90 }
91
92 /// hasByValAttr - Return true if this argument has the byval attribute on it
93 /// in its containing function.
94 bool Argument::hasByValAttr() const {
95   if (!isa<PointerType>(getType())) return false;
96   return getParent()->paramHasAttr(getArgNo()+1, ParamAttr::ByVal);
97 }
98
99 /// hasNoAliasAttr - Return true if this argument has the noalias attribute on
100 /// it in its containing function.
101 bool Argument::hasNoAliasAttr() const {
102   if (!isa<PointerType>(getType())) return false;
103   return getParent()->paramHasAttr(getArgNo()+1, ParamAttr::NoAlias);
104 }
105
106 /// hasSRetAttr - Return true if this argument has the sret attribute on
107 /// it in its containing function.
108 bool Argument::hasStructRetAttr() const {
109   if (!isa<PointerType>(getType())) return false;
110   if (this != getParent()->arg_begin()) return false; // StructRet param must be first param
111   return getParent()->paramHasAttr(1, ParamAttr::StructRet);
112 }
113
114
115
116
117 //===----------------------------------------------------------------------===//
118 // Helper Methods in Function
119 //===----------------------------------------------------------------------===//
120
121 const FunctionType *Function::getFunctionType() const {
122   return cast<FunctionType>(getType()->getElementType());
123 }
124
125 bool Function::isVarArg() const {
126   return getFunctionType()->isVarArg();
127 }
128
129 const Type *Function::getReturnType() const {
130   return getFunctionType()->getReturnType();
131 }
132
133 void Function::removeFromParent() {
134   getParent()->getFunctionList().remove(this);
135 }
136
137 void Function::eraseFromParent() {
138   getParent()->getFunctionList().erase(this);
139 }
140
141 /// @brief Determine whether the function has the given attribute.
142 bool Function::paramHasAttr(uint16_t i, ParameterAttributes attr) const {
143   return ParamAttrs && ParamAttrs->paramHasAttr(i, attr);
144 }
145
146 /// @brief Extract the alignment for a call or parameter (0=unknown).
147 uint16_t Function::getParamAlignment(uint16_t i) const {
148   return ParamAttrs ? ParamAttrs->getParamAlignment(i) : 0;
149 }
150
151 /// @brief Determine if the function cannot return.
152 bool Function::doesNotReturn() const {
153   return paramHasAttr(0, ParamAttr::NoReturn);
154 }
155
156 /// @brief Determine if the function cannot unwind.
157 bool Function::doesNotThrow() const {
158   return paramHasAttr(0, ParamAttr::NoUnwind);
159 }
160
161 /// @brief Determine if the function does not access memory.
162 bool Function::doesNotAccessMemory() const {
163   return paramHasAttr(0, ParamAttr::ReadNone);
164 }
165
166 /// @brief Determine if the function does not access or only reads memory.
167 bool Function::onlyReadsMemory() const {
168   return doesNotAccessMemory() || paramHasAttr(0, ParamAttr::ReadOnly);
169 }
170
171 /// @brief Determine if the function returns a structure through first 
172 /// pointer argument.
173 bool Function::hasStructRetAttr() const {
174   return paramHasAttr(1, ParamAttr::StructRet);
175 }
176
177 //===----------------------------------------------------------------------===//
178 // Function Implementation
179 //===----------------------------------------------------------------------===//
180
181 Function::Function(const FunctionType *Ty, LinkageTypes Linkage,
182                    const std::string &name, Module *ParentModule)
183   : GlobalValue(PointerType::getUnqual(Ty), 
184                 Value::FunctionVal, 0, 0, Linkage, name),
185     ParamAttrs(0) {
186   SymTab = new ValueSymbolTable();
187
188   assert((getReturnType()->isFirstClassType() ||getReturnType() == Type::VoidTy
189           || isa<StructType>(getReturnType()))
190          && "LLVM functions cannot return aggregate values!");
191
192   // If the function has arguments, mark them as lazily built.
193   if (Ty->getNumParams())
194     SubclassData = 1;   // Set the "has lazy arguments" bit.
195   
196   // Make sure that we get added to a function
197   LeakDetector::addGarbageObject(this);
198
199   if (ParentModule)
200     ParentModule->getFunctionList().push_back(this);
201 }
202
203 Function::~Function() {
204   dropAllReferences();    // After this it is safe to delete instructions.
205
206   // Delete all of the method arguments and unlink from symbol table...
207   ArgumentList.clear();
208   delete SymTab;
209
210   // Drop our reference to the parameter attributes, if any.
211   if (ParamAttrs)
212     ParamAttrs->dropRef();
213   
214   // Remove the function from the on-the-side collector table.
215   clearCollector();
216 }
217
218 void Function::BuildLazyArguments() const {
219   // Create the arguments vector, all arguments start out unnamed.
220   const FunctionType *FT = getFunctionType();
221   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
222     assert(FT->getParamType(i) != Type::VoidTy &&
223            "Cannot have void typed arguments!");
224     ArgumentList.push_back(new Argument(FT->getParamType(i)));
225   }
226   
227   // Clear the lazy arguments bit.
228   const_cast<Function*>(this)->SubclassData &= ~1;
229 }
230
231 size_t Function::arg_size() const {
232   return getFunctionType()->getNumParams();
233 }
234 bool Function::arg_empty() const {
235   return getFunctionType()->getNumParams() == 0;
236 }
237
238 void Function::setParent(Module *parent) {
239   if (getParent())
240     LeakDetector::addGarbageObject(this);
241   Parent = parent;
242   if (getParent())
243     LeakDetector::removeGarbageObject(this);
244 }
245
246 void Function::setParamAttrs(const ParamAttrsList *attrs) {
247   // Avoid deleting the ParamAttrsList if they are setting the
248   // attributes to the same list.
249   if (ParamAttrs == attrs)
250     return;
251
252   // Drop reference on the old ParamAttrsList
253   if (ParamAttrs)
254     ParamAttrs->dropRef();
255
256   // Add reference to the new ParamAttrsList
257   if (attrs)
258     attrs->addRef();
259
260   // Set the new ParamAttrsList.
261   ParamAttrs = attrs; 
262 }
263
264 // dropAllReferences() - This function causes all the subinstructions to "let
265 // go" of all references that they are maintaining.  This allows one to
266 // 'delete' a whole class at a time, even though there may be circular
267 // references... first all references are dropped, and all use counts go to
268 // zero.  Then everything is deleted for real.  Note that no operations are
269 // valid on an object that has "dropped all references", except operator
270 // delete.
271 //
272 void Function::dropAllReferences() {
273   for (iterator I = begin(), E = end(); I != E; ++I)
274     I->dropAllReferences();
275   BasicBlocks.clear();    // Delete all basic blocks...
276 }
277
278 // Maintain the collector name for each function in an on-the-side table. This
279 // saves allocating an additional word in Function for programs which do not use
280 // GC (i.e., most programs) at the cost of increased overhead for clients which
281 // do use GC.
282 static DenseMap<const Function*,PooledStringPtr> *CollectorNames;
283 static StringPool *CollectorNamePool;
284
285 bool Function::hasCollector() const {
286   return CollectorNames && CollectorNames->count(this);
287 }
288
289 const char *Function::getCollector() const {
290   assert(hasCollector() && "Function has no collector");
291   return *(*CollectorNames)[this];
292 }
293
294 void Function::setCollector(const char *Str) {
295   if (!CollectorNamePool)
296     CollectorNamePool = new StringPool();
297   if (!CollectorNames)
298     CollectorNames = new DenseMap<const Function*,PooledStringPtr>();
299   (*CollectorNames)[this] = CollectorNamePool->intern(Str);
300 }
301
302 void Function::clearCollector() {
303   if (CollectorNames) {
304     CollectorNames->erase(this);
305     if (CollectorNames->empty()) {
306       delete CollectorNames;
307       CollectorNames = 0;
308       if (CollectorNamePool->empty()) {
309         delete CollectorNamePool;
310         CollectorNamePool = 0;
311       }
312     }
313   }
314 }
315
316 /// getIntrinsicID - This method returns the ID number of the specified
317 /// function, or Intrinsic::not_intrinsic if the function is not an
318 /// intrinsic, or if the pointer is null.  This value is always defined to be
319 /// zero to allow easy checking for whether a function is intrinsic or not.  The
320 /// particular intrinsic functions which correspond to this value are defined in
321 /// llvm/Intrinsics.h.
322 ///
323 unsigned Function::getIntrinsicID(bool noAssert) const {
324   const ValueName *ValName = this->getValueName();
325   if (!ValName)
326     return 0;
327   unsigned Len = ValName->getKeyLength();
328   const char *Name = ValName->getKeyData();
329   
330   if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
331       || Name[2] != 'v' || Name[3] != 'm')
332     return 0;  // All intrinsics start with 'llvm.'
333
334   assert((Len != 5 || noAssert) && "'llvm.' is an invalid intrinsic name!");
335
336 #define GET_FUNCTION_RECOGNIZER
337 #include "llvm/Intrinsics.gen"
338 #undef GET_FUNCTION_RECOGNIZER
339   assert(noAssert && "Invalid LLVM intrinsic name");
340   return 0;
341 }
342
343 std::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) { 
344   assert(id < num_intrinsics && "Invalid intrinsic ID!");
345   const char * const Table[] = {
346     "not_intrinsic",
347 #define GET_INTRINSIC_NAME_TABLE
348 #include "llvm/Intrinsics.gen"
349 #undef GET_INTRINSIC_NAME_TABLE
350   };
351   if (numTys == 0)
352     return Table[id];
353   std::string Result(Table[id]);
354   for (unsigned i = 0; i < numTys; ++i) 
355     if (Tys[i])
356       Result += "." + MVT::getValueTypeString(MVT::getValueType(Tys[i]));
357   return Result;
358 }
359
360 const FunctionType *Intrinsic::getType(ID id, const Type **Tys, 
361                                        unsigned numTys) {
362   const Type *ResultTy = NULL;
363   std::vector<const Type*> ArgTys;
364   bool IsVarArg = false;
365   
366 #define GET_INTRINSIC_GENERATOR
367 #include "llvm/Intrinsics.gen"
368 #undef GET_INTRINSIC_GENERATOR
369
370   return FunctionType::get(ResultTy, ArgTys, IsVarArg); 
371 }
372
373 const ParamAttrsList *Intrinsic::getParamAttrs(ID id) {
374   ParamAttrsVector Attrs;
375   ParameterAttributes Attr = ParamAttr::None;
376
377 #define GET_INTRINSIC_ATTRIBUTES
378 #include "llvm/Intrinsics.gen"
379 #undef GET_INTRINSIC_ATTRIBUTES
380
381   // Intrinsics cannot throw exceptions.
382   Attr |= ParamAttr::NoUnwind;
383
384   Attrs.push_back(ParamAttrsWithIndex::get(0, Attr));
385   return ParamAttrsList::get(Attrs);
386 }
387
388 Function *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys, 
389                                     unsigned numTys) {
390   // There can never be multiple globals with the same name of different types,
391   // because intrinsics must be a specific type.
392   Function *F =
393     cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys),
394                                           getType(id, Tys, numTys)));
395   F->setParamAttrs(getParamAttrs(id));
396   return F;
397 }
398
399 Value *IntrinsicInst::StripPointerCasts(Value *Ptr) {
400   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
401     if (CE->getOpcode() == Instruction::BitCast) {
402       if (isa<PointerType>(CE->getOperand(0)->getType()))
403         return StripPointerCasts(CE->getOperand(0));
404     } else if (CE->getOpcode() == Instruction::GetElementPtr) {
405       for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
406         if (!CE->getOperand(i)->isNullValue())
407           return Ptr;
408       return StripPointerCasts(CE->getOperand(0));
409     }
410     return Ptr;
411   }
412
413   if (BitCastInst *CI = dyn_cast<BitCastInst>(Ptr)) {
414     if (isa<PointerType>(CI->getOperand(0)->getType()))
415       return StripPointerCasts(CI->getOperand(0));
416   } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
417     if (GEP->hasAllZeroIndices())
418       return StripPointerCasts(GEP->getOperand(0));
419   }
420   return Ptr;
421 }
422
423 // vim: sw=2 ai