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);
109 //===----------------------------------------------------------------------===//
110 // Helper Methods in Function
111 //===----------------------------------------------------------------------===//
113 const FunctionType *Function::getFunctionType() const {
114 return cast<FunctionType>(getType()->getElementType());
117 bool Function::isVarArg() const {
118 return getFunctionType()->isVarArg();
121 const Type *Function::getReturnType() const {
122 return getFunctionType()->getReturnType();
125 void Function::removeFromParent() {
126 getParent()->getFunctionList().remove(this);
129 void Function::eraseFromParent() {
130 getParent()->getFunctionList().erase(this);
133 /// @brief Determine whether the function has the given attribute.
134 bool Function::paramHasAttr(uint16_t i, unsigned attr) const {
135 return ParamAttrs && ParamAttrs->paramHasAttr(i, (ParameterAttributes)attr);
138 /// @brief Determine if the function cannot return.
139 bool Function::doesNotReturn() const {
140 return paramHasAttr(0, ParamAttr::NoReturn);
143 /// @brief Determine if the function cannot unwind.
144 bool Function::doesNotThrow() const {
145 return paramHasAttr(0, ParamAttr::NoUnwind);
148 /// @brief Determine if the function does not access memory.
149 bool Function::doesNotAccessMemory() const {
150 return paramHasAttr(0, ParamAttr::ReadNone);
153 /// @brief Determine if the function does not access or only reads memory.
154 bool Function::onlyReadsMemory() const {
155 return doesNotAccessMemory() || paramHasAttr(0, ParamAttr::ReadOnly);
158 /// @brief Determine if the function returns a structure.
159 bool Function::isStructReturn() const {
160 return paramHasAttr(1, ParamAttr::StructRet);
163 //===----------------------------------------------------------------------===//
164 // Function Implementation
165 //===----------------------------------------------------------------------===//
167 Function::Function(const FunctionType *Ty, LinkageTypes Linkage,
168 const std::string &name, Module *ParentModule)
169 : GlobalValue(PointerType::getUnqual(Ty),
170 Value::FunctionVal, 0, 0, Linkage, name),
172 SymTab = new ValueSymbolTable();
174 assert((getReturnType()->isFirstClassType() ||getReturnType() == Type::VoidTy)
175 && "LLVM functions cannot return aggregate values!");
177 // If the function has arguments, mark them as lazily built.
178 if (Ty->getNumParams())
179 SubclassData = 1; // Set the "has lazy arguments" bit.
181 // Make sure that we get added to a function
182 LeakDetector::addGarbageObject(this);
185 ParentModule->getFunctionList().push_back(this);
188 Function::~Function() {
189 dropAllReferences(); // After this it is safe to delete instructions.
191 // Delete all of the method arguments and unlink from symbol table...
192 ArgumentList.clear();
195 // Drop our reference to the parameter attributes, if any.
197 ParamAttrs->dropRef();
199 // Remove the function from the on-the-side collector table.
203 void Function::BuildLazyArguments() const {
204 // Create the arguments vector, all arguments start out unnamed.
205 const FunctionType *FT = getFunctionType();
206 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
207 assert(FT->getParamType(i) != Type::VoidTy &&
208 "Cannot have void typed arguments!");
209 ArgumentList.push_back(new Argument(FT->getParamType(i)));
212 // Clear the lazy arguments bit.
213 const_cast<Function*>(this)->SubclassData &= ~1;
216 size_t Function::arg_size() const {
217 return getFunctionType()->getNumParams();
219 bool Function::arg_empty() const {
220 return getFunctionType()->getNumParams() == 0;
223 void Function::setParent(Module *parent) {
225 LeakDetector::addGarbageObject(this);
228 LeakDetector::removeGarbageObject(this);
231 void Function::setParamAttrs(const ParamAttrsList *attrs) {
232 // Avoid deleting the ParamAttrsList if they are setting the
233 // attributes to the same list.
234 if (ParamAttrs == attrs)
237 // Drop reference on the old ParamAttrsList
239 ParamAttrs->dropRef();
241 // Add reference to the new ParamAttrsList
245 // Set the new ParamAttrsList.
249 // dropAllReferences() - This function causes all the subinstructions to "let
250 // go" of all references that they are maintaining. This allows one to
251 // 'delete' a whole class at a time, even though there may be circular
252 // references... first all references are dropped, and all use counts go to
253 // zero. Then everything is deleted for real. Note that no operations are
254 // valid on an object that has "dropped all references", except operator
257 void Function::dropAllReferences() {
258 for (iterator I = begin(), E = end(); I != E; ++I)
259 I->dropAllReferences();
260 BasicBlocks.clear(); // Delete all basic blocks...
263 // Maintain the collector name for each function in an on-the-side table. This
264 // saves allocating an additional word in Function for programs which do not use
265 // GC (i.e., most programs) at the cost of increased overhead for clients which
267 static DenseMap<const Function*,PooledStringPtr> *CollectorNames;
268 static StringPool *CollectorNamePool;
270 bool Function::hasCollector() const {
271 return CollectorNames && CollectorNames->count(this);
274 const char *Function::getCollector() const {
275 assert(hasCollector() && "Function has no collector");
276 return *(*CollectorNames)[this];
279 void Function::setCollector(const char *Str) {
280 if (!CollectorNamePool)
281 CollectorNamePool = new StringPool();
283 CollectorNames = new DenseMap<const Function*,PooledStringPtr>();
284 (*CollectorNames)[this] = CollectorNamePool->intern(Str);
287 void Function::clearCollector() {
288 if (CollectorNames) {
289 CollectorNames->erase(this);
290 if (CollectorNames->empty()) {
291 delete CollectorNames;
293 if (CollectorNamePool->empty()) {
294 delete CollectorNamePool;
295 CollectorNamePool = 0;
301 /// getIntrinsicID - This method returns the ID number of the specified
302 /// function, or Intrinsic::not_intrinsic if the function is not an
303 /// intrinsic, or if the pointer is null. This value is always defined to be
304 /// zero to allow easy checking for whether a function is intrinsic or not. The
305 /// particular intrinsic functions which correspond to this value are defined in
306 /// llvm/Intrinsics.h.
308 unsigned Function::getIntrinsicID(bool noAssert) const {
309 const ValueName *ValName = this->getValueName();
312 unsigned Len = ValName->getKeyLength();
313 const char *Name = ValName->getKeyData();
315 if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
316 || Name[2] != 'v' || Name[3] != 'm')
317 return 0; // All intrinsics start with 'llvm.'
319 assert((Len != 5 || noAssert) && "'llvm.' is an invalid intrinsic name!");
321 #define GET_FUNCTION_RECOGNIZER
322 #include "llvm/Intrinsics.gen"
323 #undef GET_FUNCTION_RECOGNIZER
324 assert(noAssert && "Invalid LLVM intrinsic name");
328 std::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) {
329 assert(id < num_intrinsics && "Invalid intrinsic ID!");
330 const char * const Table[] = {
332 #define GET_INTRINSIC_NAME_TABLE
333 #include "llvm/Intrinsics.gen"
334 #undef GET_INTRINSIC_NAME_TABLE
338 std::string Result(Table[id]);
339 for (unsigned i = 0; i < numTys; ++i)
341 Result += "." + MVT::getValueTypeString(MVT::getValueType(Tys[i]));
345 const FunctionType *Intrinsic::getType(ID id, const Type **Tys,
347 const Type *ResultTy = NULL;
348 std::vector<const Type*> ArgTys;
349 bool IsVarArg = false;
351 #define GET_INTRINSIC_GENERATOR
352 #include "llvm/Intrinsics.gen"
353 #undef GET_INTRINSIC_GENERATOR
355 return FunctionType::get(ResultTy, ArgTys, IsVarArg);
358 const ParamAttrsList *Intrinsic::getParamAttrs(ID id) {
359 ParamAttrsVector Attrs;
360 uint16_t Attr = ParamAttr::None;
362 #define GET_INTRINSIC_ATTRIBUTES
363 #include "llvm/Intrinsics.gen"
364 #undef GET_INTRINSIC_ATTRIBUTES
366 // Intrinsics cannot throw exceptions.
367 Attr |= ParamAttr::NoUnwind;
369 Attrs.push_back(ParamAttrsWithIndex::get(0, Attr));
370 return ParamAttrsList::get(Attrs);
373 Function *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys,
375 // There can never be multiple globals with the same name of different types,
376 // because intrinsics must be a specific type.
378 cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys),
379 getType(id, Tys, numTys)));
380 F->setParamAttrs(getParamAttrs(id));
384 Value *IntrinsicInst::StripPointerCasts(Value *Ptr) {
385 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
386 if (CE->getOpcode() == Instruction::BitCast) {
387 if (isa<PointerType>(CE->getOperand(0)->getType()))
388 return StripPointerCasts(CE->getOperand(0));
389 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
390 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
391 if (!CE->getOperand(i)->isNullValue())
393 return StripPointerCasts(CE->getOperand(0));
398 if (BitCastInst *CI = dyn_cast<BitCastInst>(Ptr)) {
399 if (isa<PointerType>(CI->getOperand(0)->getType()))
400 return StripPointerCasts(CI->getOperand(0));
401 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
402 if (GEP->hasAllZeroIndices())
403 return StripPointerCasts(GEP->getOperand(0));