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/ManagedStatic.h"
20 #include "llvm/Support/StringPool.h"
21 #include "llvm/System/RWMutex.h"
22 #include "llvm/System/Threading.h"
23 #include "SymbolTableListTraitsImpl.h"
24 #include "llvm/ADT/DenseMap.h"
25 #include "llvm/ADT/StringExtras.h"
29 // Explicit instantiations of SymbolTableListTraits since some of the methods
30 // are not in the public header file...
31 template class SymbolTableListTraits<Argument, Function>;
32 template class SymbolTableListTraits<BasicBlock, Function>;
34 //===----------------------------------------------------------------------===//
35 // Argument Implementation
36 //===----------------------------------------------------------------------===//
38 Argument::Argument(const Type *Ty, const std::string &Name, Function *Par)
39 : Value(Ty, Value::ArgumentVal) {
42 // Make sure that we get added to a function
43 LeakDetector::addGarbageObject(this);
46 Par->getArgumentList().push_back(this);
50 void Argument::setParent(Function *parent) {
52 LeakDetector::addGarbageObject(this);
55 LeakDetector::removeGarbageObject(this);
58 /// getArgNo - Return the index of this formal argument in its containing
59 /// function. For example in "void foo(int a, float b)" a is 0 and b is 1.
60 unsigned Argument::getArgNo() const {
61 const Function *F = getParent();
62 assert(F && "Argument is not in a function");
64 Function::const_arg_iterator AI = F->arg_begin();
66 for (; &*AI != this; ++AI)
72 /// hasByValAttr - Return true if this argument has the byval attribute on it
73 /// in its containing function.
74 bool Argument::hasByValAttr() const {
75 if (!isa<PointerType>(getType())) return false;
76 return getParent()->paramHasAttr(getArgNo()+1, Attribute::ByVal);
79 /// hasNoAliasAttr - Return true if this argument has the noalias attribute on
80 /// it in its containing function.
81 bool Argument::hasNoAliasAttr() const {
82 if (!isa<PointerType>(getType())) return false;
83 return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoAlias);
86 /// hasNoCaptureAttr - Return true if this argument has the nocapture attribute
87 /// on it in its containing function.
88 bool Argument::hasNoCaptureAttr() const {
89 if (!isa<PointerType>(getType())) return false;
90 return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoCapture);
93 /// hasSRetAttr - Return true if this argument has the sret attribute on
94 /// it in its containing function.
95 bool Argument::hasStructRetAttr() const {
96 if (!isa<PointerType>(getType())) return false;
97 if (this != getParent()->arg_begin())
98 return false; // StructRet param must be first param
99 return getParent()->paramHasAttr(1, Attribute::StructRet);
102 /// addAttr - Add a Attribute to an argument
103 void Argument::addAttr(Attributes attr) {
104 getParent()->addAttribute(getArgNo() + 1, attr);
107 /// removeAttr - Remove a Attribute from an argument
108 void Argument::removeAttr(Attributes attr) {
109 getParent()->removeAttribute(getArgNo() + 1, attr);
113 //===----------------------------------------------------------------------===//
114 // Helper Methods in Function
115 //===----------------------------------------------------------------------===//
117 LLVMContext *Function::getContext() const {
118 const Module* M = getParent();
119 if (M) return &M->getContext();
123 const FunctionType *Function::getFunctionType() const {
124 return cast<FunctionType>(getType()->getElementType());
127 bool Function::isVarArg() const {
128 return getFunctionType()->isVarArg();
131 const Type *Function::getReturnType() const {
132 return getFunctionType()->getReturnType();
135 void Function::removeFromParent() {
136 getParent()->getFunctionList().remove(this);
139 void Function::eraseFromParent() {
140 getParent()->getFunctionList().erase(this);
143 //===----------------------------------------------------------------------===//
144 // Function Implementation
145 //===----------------------------------------------------------------------===//
147 Function::Function(const FunctionType *Ty, LinkageTypes Linkage,
148 const std::string &name, Module *ParentModule)
149 : GlobalValue(PointerType::getUnqual(Ty),
150 Value::FunctionVal, 0, 0, Linkage, name) {
151 assert(FunctionType::isValidReturnType(getReturnType()) &&
152 !isa<OpaqueType>(getReturnType()) && "invalid return type");
153 SymTab = new ValueSymbolTable();
155 // If the function has arguments, mark them as lazily built.
156 if (Ty->getNumParams())
157 SubclassData = 1; // Set the "has lazy arguments" bit.
159 // Make sure that we get added to a function
160 LeakDetector::addGarbageObject(this);
163 ParentModule->getFunctionList().push_back(this);
165 // Ensure intrinsics have the right parameter attributes.
166 if (unsigned IID = getIntrinsicID())
167 setAttributes(Intrinsic::getAttributes(Intrinsic::ID(IID)));
171 Function::~Function() {
172 dropAllReferences(); // After this it is safe to delete instructions.
174 // Delete all of the method arguments and unlink from symbol table...
175 ArgumentList.clear();
178 // Remove the function from the on-the-side GC table.
182 void Function::BuildLazyArguments() const {
183 // Create the arguments vector, all arguments start out unnamed.
184 const FunctionType *FT = getFunctionType();
185 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
186 assert(FT->getParamType(i) != Type::VoidTy &&
187 "Cannot have void typed arguments!");
188 ArgumentList.push_back(new Argument(FT->getParamType(i)));
191 // Clear the lazy arguments bit.
192 const_cast<Function*>(this)->SubclassData &= ~1;
195 size_t Function::arg_size() const {
196 return getFunctionType()->getNumParams();
198 bool Function::arg_empty() const {
199 return getFunctionType()->getNumParams() == 0;
202 void Function::setParent(Module *parent) {
204 LeakDetector::addGarbageObject(this);
207 LeakDetector::removeGarbageObject(this);
210 // dropAllReferences() - This function causes all the subinstructions to "let
211 // go" of all references that they are maintaining. This allows one to
212 // 'delete' a whole class at a time, even though there may be circular
213 // references... first all references are dropped, and all use counts go to
214 // zero. Then everything is deleted for real. Note that no operations are
215 // valid on an object that has "dropped all references", except operator
218 void Function::dropAllReferences() {
219 for (iterator I = begin(), E = end(); I != E; ++I)
220 I->dropAllReferences();
221 BasicBlocks.clear(); // Delete all basic blocks...
224 void Function::addAttribute(unsigned i, Attributes attr) {
225 AttrListPtr PAL = getAttributes();
226 PAL = PAL.addAttr(i, attr);
230 void Function::removeAttribute(unsigned i, Attributes attr) {
231 AttrListPtr PAL = getAttributes();
232 PAL = PAL.removeAttr(i, attr);
236 // Maintain the GC name for each function in an on-the-side table. This saves
237 // allocating an additional word in Function for programs which do not use GC
238 // (i.e., most programs) at the cost of increased overhead for clients which do
240 static DenseMap<const Function*,PooledStringPtr> *GCNames;
241 static StringPool *GCNamePool;
242 static ManagedStatic<sys::SmartRWMutex<true> > GCLock;
244 bool Function::hasGC() const {
245 sys::SmartScopedReader<true> Reader(*GCLock);
246 return GCNames && GCNames->count(this);
249 const char *Function::getGC() const {
250 assert(hasGC() && "Function has no collector");
251 sys::SmartScopedReader<true> Reader(*GCLock);
252 return *(*GCNames)[this];
255 void Function::setGC(const char *Str) {
256 sys::SmartScopedWriter<true> Writer(*GCLock);
258 GCNamePool = new StringPool();
260 GCNames = new DenseMap<const Function*,PooledStringPtr>();
261 (*GCNames)[this] = GCNamePool->intern(Str);
264 void Function::clearGC() {
265 sys::SmartScopedWriter<true> Writer(*GCLock);
267 GCNames->erase(this);
268 if (GCNames->empty()) {
271 if (GCNamePool->empty()) {
279 /// copyAttributesFrom - copy all additional attributes (those not needed to
280 /// create a Function) from the Function Src to this one.
281 void Function::copyAttributesFrom(const GlobalValue *Src) {
282 assert(isa<Function>(Src) && "Expected a Function!");
283 GlobalValue::copyAttributesFrom(Src);
284 const Function *SrcF = cast<Function>(Src);
285 setCallingConv(SrcF->getCallingConv());
286 setAttributes(SrcF->getAttributes());
288 setGC(SrcF->getGC());
293 /// getIntrinsicID - This method returns the ID number of the specified
294 /// function, or Intrinsic::not_intrinsic if the function is not an
295 /// intrinsic, or if the pointer is null. This value is always defined to be
296 /// zero to allow easy checking for whether a function is intrinsic or not. The
297 /// particular intrinsic functions which correspond to this value are defined in
298 /// llvm/Intrinsics.h.
300 unsigned Function::getIntrinsicID() const {
301 const ValueName *ValName = this->getValueName();
304 unsigned Len = ValName->getKeyLength();
305 const char *Name = ValName->getKeyData();
307 if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
308 || Name[2] != 'v' || Name[3] != 'm')
309 return 0; // All intrinsics start with 'llvm.'
311 #define GET_FUNCTION_RECOGNIZER
312 #include "llvm/Intrinsics.gen"
313 #undef GET_FUNCTION_RECOGNIZER
317 std::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) {
318 assert(id < num_intrinsics && "Invalid intrinsic ID!");
319 const char * const Table[] = {
321 #define GET_INTRINSIC_NAME_TABLE
322 #include "llvm/Intrinsics.gen"
323 #undef GET_INTRINSIC_NAME_TABLE
327 std::string Result(Table[id]);
328 for (unsigned i = 0; i < numTys; ++i) {
329 if (const PointerType* PTyp = dyn_cast<PointerType>(Tys[i])) {
330 Result += ".p" + llvm::utostr(PTyp->getAddressSpace()) +
331 MVT::getMVT(PTyp->getElementType()).getMVTString();
334 Result += "." + MVT::getMVT(Tys[i]).getMVTString();
339 const FunctionType *Intrinsic::getType(ID id, const Type **Tys,
341 const Type *ResultTy = NULL;
342 std::vector<const Type*> ArgTys;
343 bool IsVarArg = false;
345 #define GET_INTRINSIC_GENERATOR
346 #include "llvm/Intrinsics.gen"
347 #undef GET_INTRINSIC_GENERATOR
349 return FunctionType::get(ResultTy, ArgTys, IsVarArg);
352 bool Intrinsic::isOverloaded(ID id) {
353 const bool OTable[] = {
355 #define GET_INTRINSIC_OVERLOAD_TABLE
356 #include "llvm/Intrinsics.gen"
357 #undef GET_INTRINSIC_OVERLOAD_TABLE
362 /// This defines the "Intrinsic::getAttributes(ID id)" method.
363 #define GET_INTRINSIC_ATTRIBUTES
364 #include "llvm/Intrinsics.gen"
365 #undef GET_INTRINSIC_ATTRIBUTES
367 Function *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys,
369 // There can never be multiple globals with the same name of different types,
370 // because intrinsics must be a specific type.
372 cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys),
373 getType(id, Tys, numTys)));
376 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
377 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
378 #include "llvm/Intrinsics.gen"
379 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
381 /// hasAddressTaken - returns true if there are any uses of this function
382 /// other than direct calls or invokes to it.
383 bool Function::hasAddressTaken() const {
384 for (Value::use_const_iterator I = use_begin(), E = use_end(); I != E; ++I) {
385 if (I.getOperandNo() != 0 ||
386 (!isa<CallInst>(*I) && !isa<InvokeInst>(*I)))