438fce38ec62d7736c596e8ca5e35ce436248f51
[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 was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Function & GlobalVariable classes for the VMCore
11 // library.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Module.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/IntrinsicInst.h"
18 #include "llvm/Support/LeakDetector.h"
19 #include "SymbolTableListTraitsImpl.h"
20 #include "llvm/ADT/StringExtras.h"
21 using namespace llvm;
22
23 BasicBlock *ilist_traits<BasicBlock>::createSentinel() {
24   BasicBlock *Ret = new BasicBlock();
25   // This should not be garbage monitored.
26   LeakDetector::removeGarbageObject(Ret);
27   return Ret;
28 }
29
30 iplist<BasicBlock> &ilist_traits<BasicBlock>::getList(Function *F) {
31   return F->getBasicBlockList();
32 }
33
34 Argument *ilist_traits<Argument>::createSentinel() {
35   Argument *Ret = new Argument(Type::IntTy);
36   // This should not be garbage monitored.
37   LeakDetector::removeGarbageObject(Ret);
38   return Ret;
39 }
40
41 iplist<Argument> &ilist_traits<Argument>::getList(Function *F) {
42   return F->getArgumentList();
43 }
44
45 // Explicit instantiations of SymbolTableListTraits since some of the methods
46 // are not in the public header file...
47 template class SymbolTableListTraits<Argument, Function, Function>;
48 template class SymbolTableListTraits<BasicBlock, Function, Function>;
49
50 //===----------------------------------------------------------------------===//
51 // Argument Implementation
52 //===----------------------------------------------------------------------===//
53
54 Argument::Argument(const Type *Ty, const std::string &Name, Function *Par)
55   : Value(Ty, Value::ArgumentVal, Name) {
56   Parent = 0;
57
58   // Make sure that we get added to a function
59   LeakDetector::addGarbageObject(this);
60
61   if (Par)
62     Par->getArgumentList().push_back(this);
63 }
64
65 void Argument::setParent(Function *parent) {
66   if (getParent())
67     LeakDetector::addGarbageObject(this);
68   Parent = parent;
69   if (getParent())
70     LeakDetector::removeGarbageObject(this);
71 }
72
73 //===----------------------------------------------------------------------===//
74 // Function Implementation
75 //===----------------------------------------------------------------------===//
76
77 Function::Function(const FunctionType *Ty, LinkageTypes Linkage,
78                    const std::string &name, Module *ParentModule)
79   : GlobalValue(PointerType::get(Ty), Value::FunctionVal, 0, 0, Linkage, name) {
80   CallingConvention = 0;
81   BasicBlocks.setItemParent(this);
82   BasicBlocks.setParent(this);
83   ArgumentList.setItemParent(this);
84   ArgumentList.setParent(this);
85   SymTab = new SymbolTable();
86
87   assert((getReturnType()->isFirstClassType() ||getReturnType() == Type::VoidTy)
88          && "LLVM functions cannot return aggregate values!");
89
90   // Create the arguments vector, all arguments start out unnamed.
91   for (unsigned i = 0, e = Ty->getNumParams(); i != e; ++i) {
92     assert(Ty->getParamType(i) != Type::VoidTy &&
93            "Cannot have void typed arguments!");
94     ArgumentList.push_back(new Argument(Ty->getParamType(i)));
95   }
96
97   // Make sure that we get added to a function
98   LeakDetector::addGarbageObject(this);
99
100   if (ParentModule)
101     ParentModule->getFunctionList().push_back(this);
102 }
103
104 Function::~Function() {
105   dropAllReferences();    // After this it is safe to delete instructions.
106
107   // Delete all of the method arguments and unlink from symbol table...
108   ArgumentList.clear();
109   ArgumentList.setParent(0);
110   delete SymTab;
111 }
112
113 void Function::setParent(Module *parent) {
114   if (getParent())
115     LeakDetector::addGarbageObject(this);
116   Parent = parent;
117   if (getParent())
118     LeakDetector::removeGarbageObject(this);
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 /// renameLocalSymbols - This method goes through the Function's symbol table
143 /// and renames any symbols that conflict with symbols at global scope.  This is
144 /// required before printing out to a textual form, to ensure that there is no
145 /// ambiguity when parsing.
146 void Function::renameLocalSymbols() {
147   SymbolTable &LST = getSymbolTable();                 // Local Symtab
148   SymbolTable &GST = getParent()->getSymbolTable();    // Global Symtab
149
150   for (SymbolTable::plane_iterator LPI = LST.plane_begin(), E = LST.plane_end();
151        LPI != E; ++LPI)
152     // All global symbols are of pointer type, ignore any non-pointer planes.
153     if (const PointerType *CurTy = dyn_cast<PointerType>(LPI->first)) {
154       // Only check if the global plane has any symbols of this type.
155       SymbolTable::plane_iterator GPI = GST.find(LPI->first);
156       if (GPI != GST.plane_end()) {
157         SymbolTable::ValueMap &LVM       = LPI->second;
158         const SymbolTable::ValueMap &GVM = GPI->second;
159
160         // Loop over all local symbols, renaming those that are in the global
161         // symbol table already.
162         for (SymbolTable::value_iterator VI = LVM.begin(), E = LVM.end();
163              VI != E;) {
164           Value *V                = VI->second;
165           const std::string &Name = VI->first;
166           ++VI;
167           if (GVM.count(Name)) {
168             static unsigned UniqueNum = 0;
169             // Find a name that does not conflict!
170             while (GVM.count(Name + "_" + utostr(++UniqueNum)) ||
171                    LVM.count(Name + "_" + utostr(UniqueNum)))
172               /* scan for UniqueNum that works */;
173             V->setName(Name + "_" + utostr(UniqueNum));
174           }
175         }
176       }
177     }
178 }
179
180
181 // dropAllReferences() - This function causes all the subinstructions to "let
182 // go" of all references that they are maintaining.  This allows one to
183 // 'delete' a whole class at a time, even though there may be circular
184 // references... first all references are dropped, and all use counts go to
185 // zero.  Then everything is deleted for real.  Note that no operations are
186 // valid on an object that has "dropped all references", except operator
187 // delete.
188 //
189 void Function::dropAllReferences() {
190   for (iterator I = begin(), E = end(); I != E; ++I)
191     I->dropAllReferences();
192   BasicBlocks.clear();    // Delete all basic blocks...
193 }
194
195 /// getIntrinsicID - This method returns the ID number of the specified
196 /// function, or Intrinsic::not_intrinsic if the function is not an
197 /// intrinsic, or if the pointer is null.  This value is always defined to be
198 /// zero to allow easy checking for whether a function is intrinsic or not.  The
199 /// particular intrinsic functions which correspond to this value are defined in
200 /// llvm/Intrinsics.h.
201 ///
202 unsigned Function::getIntrinsicID() const {
203   const std::string& Name = this->getName();
204   if (Name.size() < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
205       || Name[2] != 'v' || Name[3] != 'm')
206     return 0;  // All intrinsics start with 'llvm.'
207
208   assert(Name.size() != 5 && "'llvm.' is an invalid intrinsic name!");
209
210   switch (Name[5]) {
211   case 'b':
212     if (Name == "llvm.bswap.i16") return Intrinsic::bswap_i16;
213     if (Name == "llvm.bswap.i32") return Intrinsic::bswap_i32;
214     if (Name == "llvm.bswap.i64") return Intrinsic::bswap_i64;
215     break;
216   case 'c':
217     if (Name == "llvm.ctpop.i8") return Intrinsic::ctpop_i8;
218     if (Name == "llvm.ctpop.i16") return Intrinsic::ctpop_i16;
219     if (Name == "llvm.ctpop.i32") return Intrinsic::ctpop_i32;
220     if (Name == "llvm.ctpop.i64") return Intrinsic::ctpop_i64;
221     if (Name == "llvm.cttz.i8") return Intrinsic::cttz_i8;
222     if (Name == "llvm.cttz.i16") return Intrinsic::cttz_i16;
223     if (Name == "llvm.cttz.i32") return Intrinsic::cttz_i32;
224     if (Name == "llvm.cttz.i64") return Intrinsic::cttz_i64;
225     if (Name == "llvm.ctlz.i8") return Intrinsic::ctlz_i8;
226     if (Name == "llvm.ctlz.i16") return Intrinsic::ctlz_i16;
227     if (Name == "llvm.ctlz.i32") return Intrinsic::ctlz_i32;
228     if (Name == "llvm.ctlz.i64") return Intrinsic::ctlz_i64;
229     break;
230   case 'd':
231     if (Name == "llvm.dbg.stoppoint")   return Intrinsic::dbg_stoppoint;
232     if (Name == "llvm.dbg.region.start")return Intrinsic::dbg_region_start;
233     if (Name == "llvm.dbg.region.end")  return Intrinsic::dbg_region_end;
234     if (Name == "llvm.dbg.func.start")  return Intrinsic::dbg_func_start;
235     break;
236   case 'f':
237     if (Name == "llvm.frameaddress")  return Intrinsic::frameaddress;
238     break;
239   case 'g':
240     if (Name == "llvm.gcwrite") return Intrinsic::gcwrite;
241     if (Name == "llvm.gcread")  return Intrinsic::gcread;
242     if (Name == "llvm.gcroot")  return Intrinsic::gcroot;
243     break;
244   case 'i':
245     if (Name == "llvm.isunordered.f32") 
246       return Intrinsic::isunordered_f32;
247     if (Name == "llvm.isunordered.f64") 
248       return Intrinsic::isunordered_f64;
249     break;
250   case 'l':
251     if (Name == "llvm.longjmp")  return Intrinsic::longjmp;
252     break;
253   case 'm':
254     if (Name == "llvm.memcpy.i32")   return Intrinsic::memcpy_i32;
255     if (Name == "llvm.memcpy.i64")   return Intrinsic::memcpy_i64;
256     if (Name == "llvm.memmove.i32")  return Intrinsic::memmove_i32;
257     if (Name == "llvm.memmove.i64")  return Intrinsic::memmove_i64;
258     if (Name == "llvm.memset.i32")   return Intrinsic::memset_i32;
259     if (Name == "llvm.memset.i64")   return Intrinsic::memset_i64;
260     break;
261   case 'p':
262     if (Name == "llvm.prefetch")  return Intrinsic::prefetch;
263     if (Name == "llvm.pcmarker")  return Intrinsic::pcmarker;
264     break;
265   case 'r':
266     if (Name == "llvm.returnaddress")    return Intrinsic::returnaddress;
267     if (Name == "llvm.readcyclecounter") return Intrinsic::readcyclecounter;
268     break;
269   case 's':
270     if (Name == "llvm.setjmp")       return Intrinsic::setjmp;
271     if (Name == "llvm.sigsetjmp")    return Intrinsic::sigsetjmp;
272     if (Name == "llvm.siglongjmp")   return Intrinsic::siglongjmp;
273     if (Name == "llvm.stackrestore") return Intrinsic::stackrestore;
274     if (Name == "llvm.stacksave")    return Intrinsic::stacksave;
275     if (Name == "llvm.sqrt.f32")     return Intrinsic::sqrt_f32;
276     if (Name == "llvm.sqrt.f64")     return Intrinsic::sqrt_f64;
277     break;
278   case 'v':
279     if (Name == "llvm.va_copy")  return Intrinsic::vacopy;
280     if (Name == "llvm.va_end")   return Intrinsic::vaend;
281     if (Name == "llvm.va_start") return Intrinsic::vastart;
282     break;
283   }
284   // The "llvm." namespace is reserved!
285   assert(!"Unknown LLVM intrinsic function!");
286   return 0;
287 }
288
289 Value *IntrinsicInst::StripPointerCasts(Value *Ptr) {
290   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
291     if (CE->getOpcode() == Instruction::Cast) {
292       if (isa<PointerType>(CE->getOperand(0)->getType()))
293         return StripPointerCasts(CE->getOperand(0));
294     } else if (CE->getOpcode() == Instruction::GetElementPtr) {
295       for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
296         if (!CE->getOperand(i)->isNullValue())
297           return Ptr;
298       return StripPointerCasts(CE->getOperand(0));
299     }
300     return Ptr;
301   }
302
303   if (CastInst *CI = dyn_cast<CastInst>(Ptr)) {
304     if (isa<PointerType>(CI->getOperand(0)->getType()))
305       return StripPointerCasts(CI->getOperand(0));
306   } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
307     for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
308       if (!isa<Constant>(GEP->getOperand(i)) ||
309           !cast<Constant>(GEP->getOperand(i))->isNullValue())
310         return Ptr;
311     return StripPointerCasts(GEP->getOperand(0));
312   }
313   return Ptr;
314 }
315
316 // vim: sw=2 ai