1 //===-- Function.cpp - Implement the Global object classes ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Function class for the VMCore library.
12 //===----------------------------------------------------------------------===//
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"
26 BasicBlock *ilist_traits<BasicBlock>::createSentinel() {
27 BasicBlock *Ret = BasicBlock::Create();
28 // This should not be garbage monitored.
29 LeakDetector::removeGarbageObject(Ret);
33 iplist<BasicBlock> &ilist_traits<BasicBlock>::getList(Function *F) {
34 return F->getBasicBlockList();
37 Argument *ilist_traits<Argument>::createSentinel() {
38 Argument *Ret = new Argument(Type::Int32Ty);
39 // This should not be garbage monitored.
40 LeakDetector::removeGarbageObject(Ret);
44 iplist<Argument> &ilist_traits<Argument>::getList(Function *F) {
45 return F->getArgumentList();
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>;
53 //===----------------------------------------------------------------------===//
54 // Argument Implementation
55 //===----------------------------------------------------------------------===//
57 Argument::Argument(const Type *Ty, const std::string &Name, Function *Par)
58 : Value(Ty, Value::ArgumentVal) {
61 // Make sure that we get added to a function
62 LeakDetector::addGarbageObject(this);
65 Par->getArgumentList().push_back(this);
69 void Argument::setParent(Function *parent) {
71 LeakDetector::addGarbageObject(this);
74 LeakDetector::removeGarbageObject(this);
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");
83 Function::const_arg_iterator AI = F->arg_begin();
85 for (; &*AI != this; ++AI)
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);
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);
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);
116 //===----------------------------------------------------------------------===//
117 // Helper Methods in Function
118 //===----------------------------------------------------------------------===//
120 const FunctionType *Function::getFunctionType() const {
121 return cast<FunctionType>(getType()->getElementType());
124 bool Function::isVarArg() const {
125 return getFunctionType()->isVarArg();
128 const Type *Function::getReturnType() const {
129 return getFunctionType()->getReturnType();
132 void Function::removeFromParent() {
133 getParent()->getFunctionList().remove(this);
136 void Function::eraseFromParent() {
137 getParent()->getFunctionList().erase(this);
140 //===----------------------------------------------------------------------===//
141 // Function Implementation
142 //===----------------------------------------------------------------------===//
144 Function::Function(const FunctionType *Ty, LinkageTypes Linkage,
145 const std::string &name, Module *ParentModule)
146 : GlobalValue(PointerType::getUnqual(Ty),
147 Value::FunctionVal, 0, 0, Linkage, name) {
148 SymTab = new ValueSymbolTable();
150 assert((getReturnType()->isFirstClassType() ||getReturnType() == Type::VoidTy
151 || isa<StructType>(getReturnType()))
152 && "LLVM functions cannot return aggregate values!");
154 // If the function has arguments, mark them as lazily built.
155 if (Ty->getNumParams())
156 SubclassData = 1; // Set the "has lazy arguments" bit.
158 // Make sure that we get added to a function
159 LeakDetector::addGarbageObject(this);
162 ParentModule->getFunctionList().push_back(this);
164 // Ensure intrinsics have the right parameter attributes.
165 if (unsigned IID = getIntrinsicID(true))
166 setParamAttrs(Intrinsic::getParamAttrs(Intrinsic::ID(IID)));
169 Function::~Function() {
170 dropAllReferences(); // After this it is safe to delete instructions.
172 // Delete all of the method arguments and unlink from symbol table...
173 ArgumentList.clear();
176 // Remove the function from the on-the-side collector table.
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)));
189 // Clear the lazy arguments bit.
190 const_cast<Function*>(this)->SubclassData &= ~1;
193 size_t Function::arg_size() const {
194 return getFunctionType()->getNumParams();
196 bool Function::arg_empty() const {
197 return getFunctionType()->getNumParams() == 0;
200 void Function::setParent(Module *parent) {
202 LeakDetector::addGarbageObject(this);
205 LeakDetector::removeGarbageObject(this);
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
216 void Function::dropAllReferences() {
217 for (iterator I = begin(), E = end(); I != E; ++I)
218 I->dropAllReferences();
219 BasicBlocks.clear(); // Delete all basic blocks...
222 void Function::setDoesNotThrow(bool doesNotThrow) {
223 PAListPtr PAL = getParamAttrs();
225 PAL = PAL.addAttr(0, ParamAttr::NoUnwind);
227 PAL = PAL.removeAttr(0, ParamAttr::NoUnwind);
231 // Maintain the collector name for each function in an on-the-side table. This
232 // saves allocating an additional word in Function for programs which do not use
233 // GC (i.e., most programs) at the cost of increased overhead for clients which
235 static DenseMap<const Function*,PooledStringPtr> *CollectorNames;
236 static StringPool *CollectorNamePool;
238 bool Function::hasCollector() const {
239 return CollectorNames && CollectorNames->count(this);
242 const char *Function::getCollector() const {
243 assert(hasCollector() && "Function has no collector");
244 return *(*CollectorNames)[this];
247 void Function::setCollector(const char *Str) {
248 if (!CollectorNamePool)
249 CollectorNamePool = new StringPool();
251 CollectorNames = new DenseMap<const Function*,PooledStringPtr>();
252 (*CollectorNames)[this] = CollectorNamePool->intern(Str);
255 void Function::clearCollector() {
256 if (CollectorNames) {
257 CollectorNames->erase(this);
258 if (CollectorNames->empty()) {
259 delete CollectorNames;
261 if (CollectorNamePool->empty()) {
262 delete CollectorNamePool;
263 CollectorNamePool = 0;
269 /// getIntrinsicID - This method returns the ID number of the specified
270 /// function, or Intrinsic::not_intrinsic if the function is not an
271 /// intrinsic, or if the pointer is null. This value is always defined to be
272 /// zero to allow easy checking for whether a function is intrinsic or not. The
273 /// particular intrinsic functions which correspond to this value are defined in
274 /// llvm/Intrinsics.h.
276 unsigned Function::getIntrinsicID(bool noAssert) const {
277 const ValueName *ValName = this->getValueName();
280 unsigned Len = ValName->getKeyLength();
281 const char *Name = ValName->getKeyData();
283 if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
284 || Name[2] != 'v' || Name[3] != 'm')
285 return 0; // All intrinsics start with 'llvm.'
287 assert((Len != 5 || noAssert) && "'llvm.' is an invalid intrinsic name!");
289 #define GET_FUNCTION_RECOGNIZER
290 #include "llvm/Intrinsics.gen"
291 #undef GET_FUNCTION_RECOGNIZER
292 assert(noAssert && "Invalid LLVM intrinsic name");
296 std::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) {
297 assert(id < num_intrinsics && "Invalid intrinsic ID!");
298 const char * const Table[] = {
300 #define GET_INTRINSIC_NAME_TABLE
301 #include "llvm/Intrinsics.gen"
302 #undef GET_INTRINSIC_NAME_TABLE
306 std::string Result(Table[id]);
307 for (unsigned i = 0; i < numTys; ++i)
309 Result += "." + MVT::getValueTypeString(MVT::getValueType(Tys[i]));
313 const FunctionType *Intrinsic::getType(ID id, const Type **Tys,
315 const Type *ResultTy = NULL;
316 std::vector<const Type*> ArgTys;
317 bool IsVarArg = false;
319 #define GET_INTRINSIC_GENERATOR
320 #include "llvm/Intrinsics.gen"
321 #undef GET_INTRINSIC_GENERATOR
323 return FunctionType::get(ResultTy, ArgTys, IsVarArg);
326 PAListPtr Intrinsic::getParamAttrs(ID id) {
327 ParameterAttributes Attr = ParamAttr::None;
329 #define GET_INTRINSIC_ATTRIBUTES
330 #include "llvm/Intrinsics.gen"
331 #undef GET_INTRINSIC_ATTRIBUTES
333 // Intrinsics cannot throw exceptions.
334 Attr |= ParamAttr::NoUnwind;
336 ParamAttrsWithIndex PAWI = ParamAttrsWithIndex::get(0, Attr);
337 return PAListPtr::get(&PAWI, 1);
340 Function *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys,
342 // There can never be multiple globals with the same name of different types,
343 // because intrinsics must be a specific type.
345 cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys),
346 getType(id, Tys, numTys)));
349 Value *IntrinsicInst::StripPointerCasts(Value *Ptr) {
350 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
351 if (CE->getOpcode() == Instruction::BitCast) {
352 if (isa<PointerType>(CE->getOperand(0)->getType()))
353 return StripPointerCasts(CE->getOperand(0));
354 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
355 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
356 if (!CE->getOperand(i)->isNullValue())
358 return StripPointerCasts(CE->getOperand(0));
363 if (BitCastInst *CI = dyn_cast<BitCastInst>(Ptr)) {
364 if (isa<PointerType>(CI->getOperand(0)->getType()))
365 return StripPointerCasts(CI->getOperand(0));
366 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
367 if (GEP->hasAllZeroIndices())
368 return StripPointerCasts(GEP->getOperand(0));