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/ParameterAttributes.h"
18 #include "llvm/CodeGen/ValueTypes.h"
19 #include "llvm/Support/LeakDetector.h"
20 #include "llvm/Support/StringPool.h"
21 #include "SymbolTableListTraitsImpl.h"
22 #include "llvm/ADT/BitVector.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/StringExtras.h"
27 BasicBlock *ilist_traits<BasicBlock>::createSentinel() {
28 BasicBlock *Ret = new BasicBlock();
29 // This should not be garbage monitored.
30 LeakDetector::removeGarbageObject(Ret);
34 iplist<BasicBlock> &ilist_traits<BasicBlock>::getList(Function *F) {
35 return F->getBasicBlockList();
38 Argument *ilist_traits<Argument>::createSentinel() {
39 Argument *Ret = new Argument(Type::Int32Ty);
40 // This should not be garbage monitored.
41 LeakDetector::removeGarbageObject(Ret);
45 iplist<Argument> &ilist_traits<Argument>::getList(Function *F) {
46 return F->getArgumentList();
49 // Explicit instantiations of SymbolTableListTraits since some of the methods
50 // are not in the public header file...
51 template class SymbolTableListTraits<Argument, Function>;
52 template class SymbolTableListTraits<BasicBlock, Function>;
54 //===----------------------------------------------------------------------===//
55 // Argument Implementation
56 //===----------------------------------------------------------------------===//
58 Argument::Argument(const Type *Ty, const std::string &Name, Function *Par)
59 : Value(Ty, Value::ArgumentVal) {
62 // Make sure that we get added to a function
63 LeakDetector::addGarbageObject(this);
66 Par->getArgumentList().push_back(this);
70 void Argument::setParent(Function *parent) {
72 LeakDetector::addGarbageObject(this);
75 LeakDetector::removeGarbageObject(this);
78 /// getArgNo - Return the index of this formal argument in its containing
79 /// function. For example in "void foo(int a, float b)" a is 0 and b is 1.
80 unsigned Argument::getArgNo() const {
81 const Function *F = getParent();
82 assert(F && "Argument is not in a function");
84 Function::const_arg_iterator AI = F->arg_begin();
86 for (; &*AI != this; ++AI)
92 /// hasByValAttr - Return true if this argument has the byval attribute on it
93 /// in its containing function.
94 bool Argument::hasByValAttr() const {
95 if (!isa<PointerType>(getType())) return false;
96 return getParent()->paramHasAttr(getArgNo()+1, ParamAttr::ByVal);
99 /// hasNoAliasAttr - Return true if this argument has the noalias attribute on
100 /// it in its containing function.
101 bool Argument::hasNoAliasAttr() const {
102 if (!isa<PointerType>(getType())) return false;
103 return getParent()->paramHasAttr(getArgNo()+1, ParamAttr::NoAlias);
106 /// hasSRetAttr - Return true if this argument has the sret attribute on
107 /// it in its containing function.
108 bool Argument::hasStructRetAttr() const {
109 if (!isa<PointerType>(getType())) return false;
110 if (this != getParent()->arg_begin()) return false; // StructRet param must be first param
111 return getParent()->paramHasAttr(1, ParamAttr::StructRet);
117 //===----------------------------------------------------------------------===//
118 // Helper Methods in Function
119 //===----------------------------------------------------------------------===//
121 const FunctionType *Function::getFunctionType() const {
122 return cast<FunctionType>(getType()->getElementType());
125 bool Function::isVarArg() const {
126 return getFunctionType()->isVarArg();
129 const Type *Function::getReturnType() const {
130 return getFunctionType()->getReturnType();
133 void Function::removeFromParent() {
134 getParent()->getFunctionList().remove(this);
137 void Function::eraseFromParent() {
138 getParent()->getFunctionList().erase(this);
141 /// @brief Determine whether the function has the given attribute.
142 bool Function::paramHasAttr(uint16_t i, ParameterAttributes attr) const {
143 return ParamAttrs && ParamAttrs->paramHasAttr(i, attr);
146 /// @brief Determine if the function cannot return.
147 bool Function::doesNotReturn() const {
148 return paramHasAttr(0, ParamAttr::NoReturn);
151 /// @brief Determine if the function cannot unwind.
152 bool Function::doesNotThrow() const {
153 return paramHasAttr(0, ParamAttr::NoUnwind);
156 /// @brief Determine if the function does not access memory.
157 bool Function::doesNotAccessMemory() const {
158 return paramHasAttr(0, ParamAttr::ReadNone);
161 /// @brief Determine if the function does not access or only reads memory.
162 bool Function::onlyReadsMemory() const {
163 return doesNotAccessMemory() || paramHasAttr(0, ParamAttr::ReadOnly);
166 /// @brief Determine if the function returns a structure.
167 bool Function::isStructReturn() const {
168 return paramHasAttr(1, ParamAttr::StructRet);
171 //===----------------------------------------------------------------------===//
172 // Function Implementation
173 //===----------------------------------------------------------------------===//
175 Function::Function(const FunctionType *Ty, LinkageTypes Linkage,
176 const std::string &name, Module *ParentModule)
177 : GlobalValue(PointerType::getUnqual(Ty),
178 Value::FunctionVal, 0, 0, Linkage, name),
180 SymTab = new ValueSymbolTable();
182 assert((getReturnType()->isFirstClassType() ||getReturnType() == Type::VoidTy
183 || isa<StructType>(getReturnType()))
184 && "LLVM functions cannot return aggregate values!");
186 // If the function has arguments, mark them as lazily built.
187 if (Ty->getNumParams())
188 SubclassData = 1; // Set the "has lazy arguments" bit.
190 // Make sure that we get added to a function
191 LeakDetector::addGarbageObject(this);
194 ParentModule->getFunctionList().push_back(this);
197 Function::~Function() {
198 dropAllReferences(); // After this it is safe to delete instructions.
200 // Delete all of the method arguments and unlink from symbol table...
201 ArgumentList.clear();
204 // Drop our reference to the parameter attributes, if any.
206 ParamAttrs->dropRef();
208 // Remove the function from the on-the-side collector table.
212 void Function::BuildLazyArguments() const {
213 // Create the arguments vector, all arguments start out unnamed.
214 const FunctionType *FT = getFunctionType();
215 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
216 assert(FT->getParamType(i) != Type::VoidTy &&
217 "Cannot have void typed arguments!");
218 ArgumentList.push_back(new Argument(FT->getParamType(i)));
221 // Clear the lazy arguments bit.
222 const_cast<Function*>(this)->SubclassData &= ~1;
225 size_t Function::arg_size() const {
226 return getFunctionType()->getNumParams();
228 bool Function::arg_empty() const {
229 return getFunctionType()->getNumParams() == 0;
232 void Function::setParent(Module *parent) {
234 LeakDetector::addGarbageObject(this);
237 LeakDetector::removeGarbageObject(this);
240 void Function::setParamAttrs(const ParamAttrsList *attrs) {
241 // Avoid deleting the ParamAttrsList if they are setting the
242 // attributes to the same list.
243 if (ParamAttrs == attrs)
246 // Drop reference on the old ParamAttrsList
248 ParamAttrs->dropRef();
250 // Add reference to the new ParamAttrsList
254 // Set the new ParamAttrsList.
258 // dropAllReferences() - This function causes all the subinstructions to "let
259 // go" of all references that they are maintaining. This allows one to
260 // 'delete' a whole class at a time, even though there may be circular
261 // references... first all references are dropped, and all use counts go to
262 // zero. Then everything is deleted for real. Note that no operations are
263 // valid on an object that has "dropped all references", except operator
266 void Function::dropAllReferences() {
267 for (iterator I = begin(), E = end(); I != E; ++I)
268 I->dropAllReferences();
269 BasicBlocks.clear(); // Delete all basic blocks...
272 // Maintain the collector name for each function in an on-the-side table. This
273 // saves allocating an additional word in Function for programs which do not use
274 // GC (i.e., most programs) at the cost of increased overhead for clients which
276 static DenseMap<const Function*,PooledStringPtr> *CollectorNames;
277 static StringPool *CollectorNamePool;
279 bool Function::hasCollector() const {
280 return CollectorNames && CollectorNames->count(this);
283 const char *Function::getCollector() const {
284 assert(hasCollector() && "Function has no collector");
285 return *(*CollectorNames)[this];
288 void Function::setCollector(const char *Str) {
289 if (!CollectorNamePool)
290 CollectorNamePool = new StringPool();
292 CollectorNames = new DenseMap<const Function*,PooledStringPtr>();
293 (*CollectorNames)[this] = CollectorNamePool->intern(Str);
296 void Function::clearCollector() {
297 if (CollectorNames) {
298 CollectorNames->erase(this);
299 if (CollectorNames->empty()) {
300 delete CollectorNames;
302 if (CollectorNamePool->empty()) {
303 delete CollectorNamePool;
304 CollectorNamePool = 0;
310 /// getIntrinsicID - This method returns the ID number of the specified
311 /// function, or Intrinsic::not_intrinsic if the function is not an
312 /// intrinsic, or if the pointer is null. This value is always defined to be
313 /// zero to allow easy checking for whether a function is intrinsic or not. The
314 /// particular intrinsic functions which correspond to this value are defined in
315 /// llvm/Intrinsics.h.
317 unsigned Function::getIntrinsicID(bool noAssert) const {
318 const ValueName *ValName = this->getValueName();
321 unsigned Len = ValName->getKeyLength();
322 const char *Name = ValName->getKeyData();
324 if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
325 || Name[2] != 'v' || Name[3] != 'm')
326 return 0; // All intrinsics start with 'llvm.'
328 assert((Len != 5 || noAssert) && "'llvm.' is an invalid intrinsic name!");
330 #define GET_FUNCTION_RECOGNIZER
331 #include "llvm/Intrinsics.gen"
332 #undef GET_FUNCTION_RECOGNIZER
333 assert(noAssert && "Invalid LLVM intrinsic name");
337 std::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) {
338 assert(id < num_intrinsics && "Invalid intrinsic ID!");
339 const char * const Table[] = {
341 #define GET_INTRINSIC_NAME_TABLE
342 #include "llvm/Intrinsics.gen"
343 #undef GET_INTRINSIC_NAME_TABLE
347 std::string Result(Table[id]);
348 for (unsigned i = 0; i < numTys; ++i)
350 Result += "." + MVT::getValueTypeString(MVT::getValueType(Tys[i]));
354 const FunctionType *Intrinsic::getType(ID id, const Type **Tys,
356 const Type *ResultTy = NULL;
357 std::vector<const Type*> ArgTys;
358 bool IsVarArg = false;
360 #define GET_INTRINSIC_GENERATOR
361 #include "llvm/Intrinsics.gen"
362 #undef GET_INTRINSIC_GENERATOR
364 return FunctionType::get(ResultTy, ArgTys, IsVarArg);
367 const ParamAttrsList *Intrinsic::getParamAttrs(ID id) {
368 ParamAttrsVector Attrs;
369 ParameterAttributes Attr = ParamAttr::None;
371 #define GET_INTRINSIC_ATTRIBUTES
372 #include "llvm/Intrinsics.gen"
373 #undef GET_INTRINSIC_ATTRIBUTES
375 // Intrinsics cannot throw exceptions.
376 Attr |= ParamAttr::NoUnwind;
378 Attrs.push_back(ParamAttrsWithIndex::get(0, Attr));
379 return ParamAttrsList::get(Attrs);
382 Function *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys,
384 // There can never be multiple globals with the same name of different types,
385 // because intrinsics must be a specific type.
387 cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys),
388 getType(id, Tys, numTys)));
389 F->setParamAttrs(getParamAttrs(id));
393 Value *IntrinsicInst::StripPointerCasts(Value *Ptr) {
394 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
395 if (CE->getOpcode() == Instruction::BitCast) {
396 if (isa<PointerType>(CE->getOperand(0)->getType()))
397 return StripPointerCasts(CE->getOperand(0));
398 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
399 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
400 if (!CE->getOperand(i)->isNullValue())
402 return StripPointerCasts(CE->getOperand(0));
407 if (BitCastInst *CI = dyn_cast<BitCastInst>(Ptr)) {
408 if (isa<PointerType>(CI->getOperand(0)->getType()))
409 return StripPointerCasts(CI->getOperand(0));
410 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
411 if (GEP->hasAllZeroIndices())
412 return StripPointerCasts(GEP->getOperand(0));