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/LLVMContext.h"
18 #include "llvm/CodeGen/ValueTypes.h"
19 #include "llvm/Support/LeakDetector.h"
20 #include "llvm/Support/ManagedStatic.h"
21 #include "llvm/Support/StringPool.h"
22 #include "llvm/System/RWMutex.h"
23 #include "llvm/System/Threading.h"
24 #include "SymbolTableListTraitsImpl.h"
25 #include "llvm/ADT/DenseMap.h"
26 #include "llvm/ADT/StringExtras.h"
30 // Explicit instantiations of SymbolTableListTraits since some of the methods
31 // are not in the public header file...
32 template class SymbolTableListTraits<Argument, Function>;
33 template class SymbolTableListTraits<BasicBlock, Function>;
35 //===----------------------------------------------------------------------===//
36 // Argument Implementation
37 //===----------------------------------------------------------------------===//
39 Argument::Argument(const Type *Ty, const Twine &Name, Function *Par)
40 : Value(Ty, Value::ArgumentVal) {
43 // Make sure that we get added to a function
44 LeakDetector::addGarbageObject(this);
47 Par->getArgumentList().push_back(this);
51 void Argument::setParent(Function *parent) {
53 LeakDetector::addGarbageObject(this);
56 LeakDetector::removeGarbageObject(this);
59 /// getArgNo - Return the index of this formal argument in its containing
60 /// function. For example in "void foo(int a, float b)" a is 0 and b is 1.
61 unsigned Argument::getArgNo() const {
62 const Function *F = getParent();
63 assert(F && "Argument is not in a function");
65 Function::const_arg_iterator AI = F->arg_begin();
67 for (; &*AI != this; ++AI)
73 /// hasByValAttr - Return true if this argument has the byval attribute on it
74 /// in its containing function.
75 bool Argument::hasByValAttr() const {
76 if (!isa<PointerType>(getType())) return false;
77 return getParent()->paramHasAttr(getArgNo()+1, Attribute::ByVal);
80 /// hasNestAttr - Return true if this argument has the nest attribute on
81 /// it in its containing function.
82 bool Argument::hasNestAttr() const {
83 if (!isa<PointerType>(getType())) return false;
84 return getParent()->paramHasAttr(getArgNo()+1, Attribute::Nest);
87 /// hasNoAliasAttr - Return true if this argument has the noalias attribute on
88 /// it in its containing function.
89 bool Argument::hasNoAliasAttr() const {
90 if (!isa<PointerType>(getType())) return false;
91 return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoAlias);
94 /// hasNoCaptureAttr - Return true if this argument has the nocapture attribute
95 /// on it in its containing function.
96 bool Argument::hasNoCaptureAttr() const {
97 if (!isa<PointerType>(getType())) return false;
98 return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoCapture);
101 /// hasSRetAttr - Return true if this argument has the sret attribute on
102 /// it in its containing function.
103 bool Argument::hasStructRetAttr() const {
104 if (!isa<PointerType>(getType())) return false;
105 if (this != getParent()->arg_begin())
106 return false; // StructRet param must be first param
107 return getParent()->paramHasAttr(1, Attribute::StructRet);
110 /// addAttr - Add a Attribute to an argument
111 void Argument::addAttr(Attributes attr) {
112 getParent()->addAttribute(getArgNo() + 1, attr);
115 /// removeAttr - Remove a Attribute from an argument
116 void Argument::removeAttr(Attributes attr) {
117 getParent()->removeAttribute(getArgNo() + 1, attr);
121 //===----------------------------------------------------------------------===//
122 // Helper Methods in Function
123 //===----------------------------------------------------------------------===//
125 LLVMContext &Function::getContext() const {
126 return getType()->getContext();
129 const FunctionType *Function::getFunctionType() const {
130 return cast<FunctionType>(getType()->getElementType());
133 bool Function::isVarArg() const {
134 return getFunctionType()->isVarArg();
137 const Type *Function::getReturnType() const {
138 return getFunctionType()->getReturnType();
141 void Function::removeFromParent() {
142 getParent()->getFunctionList().remove(this);
145 void Function::eraseFromParent() {
146 getParent()->getFunctionList().erase(this);
149 //===----------------------------------------------------------------------===//
150 // Function Implementation
151 //===----------------------------------------------------------------------===//
153 Function::Function(const FunctionType *Ty, LinkageTypes Linkage,
154 const Twine &name, Module *ParentModule)
155 : GlobalValue(PointerType::getUnqual(Ty),
156 Value::FunctionVal, 0, 0, Linkage, name) {
157 assert(FunctionType::isValidReturnType(getReturnType()) &&
158 !isa<OpaqueType>(getReturnType()) && "invalid return type");
159 SymTab = new ValueSymbolTable();
161 // If the function has arguments, mark them as lazily built.
162 if (Ty->getNumParams())
163 SubclassData = 1; // Set the "has lazy arguments" bit.
165 // Make sure that we get added to a function
166 LeakDetector::addGarbageObject(this);
169 ParentModule->getFunctionList().push_back(this);
171 // Ensure intrinsics have the right parameter attributes.
172 if (unsigned IID = getIntrinsicID())
173 setAttributes(Intrinsic::getAttributes(Intrinsic::ID(IID)));
177 Function::~Function() {
178 dropAllReferences(); // After this it is safe to delete instructions.
180 // Delete all of the method arguments and unlink from symbol table...
181 ArgumentList.clear();
184 // Remove the function from the on-the-side GC table.
188 void Function::BuildLazyArguments() const {
189 // Create the arguments vector, all arguments start out unnamed.
190 const FunctionType *FT = getFunctionType();
191 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
192 assert(FT->getParamType(i) != Type::getVoidTy(FT->getContext()) &&
193 "Cannot have void typed arguments!");
194 ArgumentList.push_back(new Argument(FT->getParamType(i)));
197 // Clear the lazy arguments bit.
198 const_cast<Function*>(this)->SubclassData &= ~1;
201 size_t Function::arg_size() const {
202 return getFunctionType()->getNumParams();
204 bool Function::arg_empty() const {
205 return getFunctionType()->getNumParams() == 0;
208 void Function::setParent(Module *parent) {
210 LeakDetector::addGarbageObject(this);
213 LeakDetector::removeGarbageObject(this);
216 // dropAllReferences() - This function causes all the subinstructions to "let
217 // go" of all references that they are maintaining. This allows one to
218 // 'delete' a whole class at a time, even though there may be circular
219 // references... first all references are dropped, and all use counts go to
220 // zero. Then everything is deleted for real. Note that no operations are
221 // valid on an object that has "dropped all references", except operator
224 void Function::dropAllReferences() {
225 for (iterator I = begin(), E = end(); I != E; ++I)
226 I->dropAllReferences();
228 // Delete all basic blocks.
229 while (!BasicBlocks.empty()) {
230 // If there is still a reference to the block, it must be a 'blockaddress'
231 // constant pointing to it. Just replace the BlockAddress with undef.
232 BasicBlock *BB = BasicBlocks.begin();
233 if (!BB->use_empty()) {
234 BlockAddress *BA = cast<BlockAddress>(BB->use_back());
235 BA->replaceAllUsesWith(UndefValue::get(BA->getType()));
236 BA->destroyConstant();
239 BB->eraseFromParent();
243 void Function::addAttribute(unsigned i, Attributes attr) {
244 AttrListPtr PAL = getAttributes();
245 PAL = PAL.addAttr(i, attr);
249 void Function::removeAttribute(unsigned i, Attributes attr) {
250 AttrListPtr PAL = getAttributes();
251 PAL = PAL.removeAttr(i, attr);
255 // Maintain the GC name for each function in an on-the-side table. This saves
256 // allocating an additional word in Function for programs which do not use GC
257 // (i.e., most programs) at the cost of increased overhead for clients which do
259 static DenseMap<const Function*,PooledStringPtr> *GCNames;
260 static StringPool *GCNamePool;
261 static ManagedStatic<sys::SmartRWMutex<true> > GCLock;
263 bool Function::hasGC() const {
264 sys::SmartScopedReader<true> Reader(*GCLock);
265 return GCNames && GCNames->count(this);
268 const char *Function::getGC() const {
269 assert(hasGC() && "Function has no collector");
270 sys::SmartScopedReader<true> Reader(*GCLock);
271 return *(*GCNames)[this];
274 void Function::setGC(const char *Str) {
275 sys::SmartScopedWriter<true> Writer(*GCLock);
277 GCNamePool = new StringPool();
279 GCNames = new DenseMap<const Function*,PooledStringPtr>();
280 (*GCNames)[this] = GCNamePool->intern(Str);
283 void Function::clearGC() {
284 sys::SmartScopedWriter<true> Writer(*GCLock);
286 GCNames->erase(this);
287 if (GCNames->empty()) {
290 if (GCNamePool->empty()) {
298 /// copyAttributesFrom - copy all additional attributes (those not needed to
299 /// create a Function) from the Function Src to this one.
300 void Function::copyAttributesFrom(const GlobalValue *Src) {
301 assert(isa<Function>(Src) && "Expected a Function!");
302 GlobalValue::copyAttributesFrom(Src);
303 const Function *SrcF = cast<Function>(Src);
304 setCallingConv(SrcF->getCallingConv());
305 setAttributes(SrcF->getAttributes());
307 setGC(SrcF->getGC());
312 /// getIntrinsicID - This method returns the ID number of the specified
313 /// function, or Intrinsic::not_intrinsic if the function is not an
314 /// intrinsic, or if the pointer is null. This value is always defined to be
315 /// zero to allow easy checking for whether a function is intrinsic or not. The
316 /// particular intrinsic functions which correspond to this value are defined in
317 /// llvm/Intrinsics.h.
319 unsigned Function::getIntrinsicID() const {
320 const ValueName *ValName = this->getValueName();
323 unsigned Len = ValName->getKeyLength();
324 const char *Name = ValName->getKeyData();
326 if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
327 || Name[2] != 'v' || Name[3] != 'm')
328 return 0; // All intrinsics start with 'llvm.'
330 #define GET_FUNCTION_RECOGNIZER
331 #include "llvm/Intrinsics.gen"
332 #undef GET_FUNCTION_RECOGNIZER
336 std::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) {
337 assert(id < num_intrinsics && "Invalid intrinsic ID!");
338 const char * const Table[] = {
340 #define GET_INTRINSIC_NAME_TABLE
341 #include "llvm/Intrinsics.gen"
342 #undef GET_INTRINSIC_NAME_TABLE
346 std::string Result(Table[id]);
347 for (unsigned i = 0; i < numTys; ++i) {
348 if (const PointerType* PTyp = dyn_cast<PointerType>(Tys[i])) {
349 Result += ".p" + llvm::utostr(PTyp->getAddressSpace()) +
350 EVT::getEVT(PTyp->getElementType()).getEVTString();
353 Result += "." + EVT::getEVT(Tys[i]).getEVTString();
358 const FunctionType *Intrinsic::getType(LLVMContext &Context,
359 ID id, const Type **Tys,
361 const Type *ResultTy = NULL;
362 std::vector<const Type*> ArgTys;
363 bool IsVarArg = false;
365 #define GET_INTRINSIC_GENERATOR
366 #include "llvm/Intrinsics.gen"
367 #undef GET_INTRINSIC_GENERATOR
369 return FunctionType::get(ResultTy, ArgTys, IsVarArg);
372 bool Intrinsic::isOverloaded(ID id) {
373 const bool OTable[] = {
375 #define GET_INTRINSIC_OVERLOAD_TABLE
376 #include "llvm/Intrinsics.gen"
377 #undef GET_INTRINSIC_OVERLOAD_TABLE
382 /// This defines the "Intrinsic::getAttributes(ID id)" method.
383 #define GET_INTRINSIC_ATTRIBUTES
384 #include "llvm/Intrinsics.gen"
385 #undef GET_INTRINSIC_ATTRIBUTES
387 Function *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys,
389 // There can never be multiple globals with the same name of different types,
390 // because intrinsics must be a specific type.
392 cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys),
393 getType(M->getContext(),
397 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
398 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
399 #include "llvm/Intrinsics.gen"
400 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
402 /// hasAddressTaken - returns true if there are any uses of this function
403 /// other than direct calls or invokes to it.
404 bool Function::hasAddressTaken() const {
405 for (Value::use_const_iterator I = use_begin(), E = use_end(); I != E; ++I) {
406 if (I.getOperandNo() != 0 ||
407 (!isa<CallInst>(*I) && !isa<InvokeInst>(*I)))