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