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