f61a4d2326241ce00029c813b7fbb262707a49f6
[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   BasicBlocks.setItemParent(this);
81   BasicBlocks.setParent(this);
82   ArgumentList.setItemParent(this);
83   ArgumentList.setParent(this);
84   SymTab = new SymbolTable();
85
86   assert((getReturnType()->isFirstClassType() ||getReturnType() == Type::VoidTy)
87          && "LLVM functions cannot return aggregate values!");
88
89   // Create the arguments vector, all arguments start out unnamed.
90   for (unsigned i = 0, e = Ty->getNumParams(); i != e; ++i) {
91     assert(Ty->getParamType(i) != Type::VoidTy &&
92            "Cannot have void typed arguments!");
93     ArgumentList.push_back(new Argument(Ty->getParamType(i)));
94   }
95
96   // Make sure that we get added to a function
97   LeakDetector::addGarbageObject(this);
98
99   if (ParentModule)
100     ParentModule->getFunctionList().push_back(this);
101 }
102
103 Function::~Function() {
104   dropAllReferences();    // After this it is safe to delete instructions.
105
106   // Delete all of the method arguments and unlink from symbol table...
107   ArgumentList.clear();
108   ArgumentList.setParent(0);
109   delete SymTab;
110 }
111
112 void Function::setParent(Module *parent) {
113   if (getParent())
114     LeakDetector::addGarbageObject(this);
115   Parent = parent;
116   if (getParent())
117     LeakDetector::removeGarbageObject(this);
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
141 /// renameLocalSymbols - This method goes through the Function's symbol table
142 /// and renames any symbols that conflict with symbols at global scope.  This is
143 /// required before printing out to a textual form, to ensure that there is no
144 /// ambiguity when parsing.
145 void Function::renameLocalSymbols() {
146   SymbolTable &LST = getSymbolTable();                 // Local Symtab
147   SymbolTable &GST = getParent()->getSymbolTable();    // Global Symtab
148
149   for (SymbolTable::plane_iterator LPI = LST.plane_begin(), E = LST.plane_end();
150        LPI != E; ++LPI)
151     // All global symbols are of pointer type, ignore any non-pointer planes.
152     if (const PointerType *CurTy = dyn_cast<PointerType>(LPI->first)) {
153       // Only check if the global plane has any symbols of this type.
154       SymbolTable::plane_iterator GPI = GST.find(LPI->first);
155       if (GPI != GST.plane_end()) {
156         SymbolTable::ValueMap &LVM       = LPI->second;
157         const SymbolTable::ValueMap &GVM = GPI->second;
158
159         // Loop over all local symbols, renaming those that are in the global
160         // symbol table already.
161         for (SymbolTable::value_iterator VI = LVM.begin(), E = LVM.end();
162              VI != E;) {
163           Value *V                = VI->second;
164           const std::string &Name = VI->first;
165           ++VI;
166           if (GVM.count(Name)) {
167             static unsigned UniqueNum = 0;
168             // Find a name that does not conflict!
169             while (GVM.count(Name + "_" + utostr(++UniqueNum)) ||
170                    LVM.count(Name + "_" + utostr(UniqueNum)))
171               /* scan for UniqueNum that works */;
172             V->setName(Name + "_" + utostr(UniqueNum));
173           }
174         }
175       }
176     }
177 }
178
179
180 // dropAllReferences() - This function causes all the subinstructions to "let
181 // go" of all references that they are maintaining.  This allows one to
182 // 'delete' a whole class at a time, even though there may be circular
183 // references... first all references are dropped, and all use counts go to
184 // zero.  Then everything is deleted for real.  Note that no operations are
185 // valid on an object that has "dropped all references", except operator
186 // delete.
187 //
188 void Function::dropAllReferences() {
189   for (iterator I = begin(), E = end(); I != E; ++I)
190     I->dropAllReferences();
191   BasicBlocks.clear();    // Delete all basic blocks...
192 }
193
194 /// getIntrinsicID - This method returns the ID number of the specified
195 /// function, or Intrinsic::not_intrinsic if the function is not an
196 /// intrinsic, or if the pointer is null.  This value is always defined to be
197 /// zero to allow easy checking for whether a function is intrinsic or not.  The
198 /// particular intrinsic functions which correspond to this value are defined in
199 /// llvm/Intrinsics.h.
200 ///
201 unsigned Function::getIntrinsicID() const {
202   if (getName().size() < 5 || getName()[4] != '.' || getName()[0] != 'l' ||
203       getName()[1] != 'l' || getName()[2] != 'v' || getName()[3] != 'm')
204     return 0;  // All intrinsics start with 'llvm.'
205
206   assert(getName().size() != 5 && "'llvm.' is an invalid intrinsic name!");
207
208   switch (getName()[5]) {
209   case 'c':
210     if (getName() == "llvm.ctpop") return Intrinsic::ctpop;
211     if (getName() == "llvm.cttz") return Intrinsic::cttz;
212     if (getName() == "llvm.ctlz") return Intrinsic::ctlz;
213     break;
214   case 'd':
215     if (getName() == "llvm.dbg.stoppoint")   return Intrinsic::dbg_stoppoint;
216     if (getName() == "llvm.dbg.region.start")return Intrinsic::dbg_region_start;
217     if (getName() == "llvm.dbg.region.end")  return Intrinsic::dbg_region_end;
218     if (getName() == "llvm.dbg.func.start")  return Intrinsic::dbg_func_start;
219     if (getName() == "llvm.dbg.declare")     return Intrinsic::dbg_declare;
220     break;
221   case 'f':
222     if (getName() == "llvm.frameaddress")  return Intrinsic::frameaddress;
223     break;
224   case 'g':
225     if (getName() == "llvm.gcwrite") return Intrinsic::gcwrite;
226     if (getName() == "llvm.gcread")  return Intrinsic::gcread;
227     if (getName() == "llvm.gcroot")  return Intrinsic::gcroot;
228     break;
229   case 'i':
230     if (getName() == "llvm.isunordered") return Intrinsic::isunordered;
231     break;
232   case 'l':
233     if (getName() == "llvm.longjmp")  return Intrinsic::longjmp;
234     break;
235   case 'm':
236     if (getName() == "llvm.memcpy")  return Intrinsic::memcpy;
237     if (getName() == "llvm.memmove")  return Intrinsic::memmove;
238     if (getName() == "llvm.memset")  return Intrinsic::memset;
239     break;
240   case 'p':
241     if (getName() == "llvm.prefetch")  return Intrinsic::prefetch;
242     if (getName() == "llvm.pcmarker")  return Intrinsic::pcmarker;
243     break;
244   case 'r':
245     if (getName() == "llvm.returnaddress")  return Intrinsic::returnaddress;
246     if (getName() == "llvm.readport")       return Intrinsic::readport;
247     if (getName() == "llvm.readio")         return Intrinsic::readio;
248     break;
249   case 's':
250     if (getName() == "llvm.setjmp")     return Intrinsic::setjmp;
251     if (getName() == "llvm.sigsetjmp")  return Intrinsic::sigsetjmp;
252     if (getName() == "llvm.siglongjmp") return Intrinsic::siglongjmp;
253     if (getName() == "llvm.sqrt")       return Intrinsic::sqrt;
254     break;
255   case 'v':
256     if (getName() == "llvm.va_copy")  return Intrinsic::vacopy;
257     if (getName() == "llvm.va_end")   return Intrinsic::vaend;
258     if (getName() == "llvm.va_start") return Intrinsic::vastart;
259   case 'w':
260     if (getName() == "llvm.writeport") return Intrinsic::writeport;
261     if (getName() == "llvm.writeio")   return Intrinsic::writeio;
262     break;
263   }
264   // The "llvm." namespace is reserved!
265   assert(0 && "Unknown LLVM intrinsic function!");
266   return 0;
267 }
268
269 Value *IntrinsicInst::StripPointerCasts(Value *Ptr) {
270   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
271     if (CE->getOpcode() == Instruction::Cast) {
272       if (isa<PointerType>(CE->getOperand(0)->getType()))
273         return StripPointerCasts(CE->getOperand(0));
274     } else if (CE->getOpcode() == Instruction::GetElementPtr) {
275       for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
276         if (!CE->getOperand(i)->isNullValue())
277           return Ptr;
278       return StripPointerCasts(CE->getOperand(0));
279     }
280     return Ptr;
281   }
282
283   if (CastInst *CI = dyn_cast<CastInst>(Ptr)) {
284     if (isa<PointerType>(CI->getOperand(0)->getType()))
285       return StripPointerCasts(CI->getOperand(0));
286   } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
287     for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
288       if (!isa<Constant>(GEP->getOperand(i)) ||
289           !cast<Constant>(GEP->getOperand(i))->isNullValue())
290         return Ptr;
291     return StripPointerCasts(GEP->getOperand(0));
292   }
293   return Ptr;
294 }
295
296 // vim: sw=2 ai