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