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 /// hasNoAliasAttr - Return true if this argument has the noalias attribute on
81 /// it in its containing function.
82 bool Argument::hasNoAliasAttr() const {
83 if (!isa
<PointerType
>(getType())) return false;
84 return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoAlias
);
87 /// hasNoCaptureAttr - Return true if this argument has the nocapture attribute
88 /// on it in its containing function.
89 bool Argument::hasNoCaptureAttr() const {
90 if (!isa
<PointerType
>(getType())) return false;
91 return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoCapture
);
94 /// hasSRetAttr - Return true if this argument has the sret attribute on
95 /// it in its containing function.
96 bool Argument::hasStructRetAttr() const {
97 if (!isa
<PointerType
>(getType())) return false;
98 if (this != getParent()->arg_begin())
99 return false; // StructRet param must be first param
100 return getParent()->paramHasAttr(1, Attribute::StructRet
);
103 /// addAttr - Add a Attribute to an argument
104 void Argument::addAttr(Attributes attr
) {
105 getParent()->addAttribute(getArgNo() + 1, attr
);
108 /// removeAttr - Remove a Attribute from an argument
109 void Argument::removeAttr(Attributes attr
) {
110 getParent()->removeAttribute(getArgNo() + 1, attr
);
114 //===----------------------------------------------------------------------===//
115 // Helper Methods in Function
116 //===----------------------------------------------------------------------===//
118 LLVMContext
&Function::getContext() const {
119 return getType()->getContext();
122 const FunctionType
*Function::getFunctionType() const {
123 return cast
<FunctionType
>(getType()->getElementType());
126 bool Function::isVarArg() const {
127 return getFunctionType()->isVarArg();
130 const Type
*Function::getReturnType() const {
131 return getFunctionType()->getReturnType();
134 void Function::removeFromParent() {
135 getParent()->getFunctionList().remove(this);
138 void Function::eraseFromParent() {
139 getParent()->getFunctionList().erase(this);
142 //===----------------------------------------------------------------------===//
143 // Function Implementation
144 //===----------------------------------------------------------------------===//
146 Function::Function(const FunctionType
*Ty
, LinkageTypes Linkage
,
147 const Twine
&name
, Module
*ParentModule
)
148 : GlobalValue(PointerType::getUnqual(Ty
),
149 Value::FunctionVal
, 0, 0, Linkage
, name
) {
150 assert(FunctionType::isValidReturnType(getReturnType()) &&
151 !isa
<OpaqueType
>(getReturnType()) && "invalid return type");
152 SymTab
= new ValueSymbolTable();
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())
166 setAttributes(Intrinsic::getAttributes(Intrinsic::ID(IID
)));
170 Function::~Function() {
171 dropAllReferences(); // After this it is safe to delete instructions.
173 // Delete all of the method arguments and unlink from symbol table...
174 ArgumentList
.clear();
177 // Remove the function from the on-the-side GC table.
181 void Function::BuildLazyArguments() const {
182 // Create the arguments vector, all arguments start out unnamed.
183 const FunctionType
*FT
= getFunctionType();
184 for (unsigned i
= 0, e
= FT
->getNumParams(); i
!= e
; ++i
) {
185 assert(FT
->getParamType(i
) != Type::getVoidTy(FT
->getContext()) &&
186 "Cannot have void typed arguments!");
187 ArgumentList
.push_back(new Argument(FT
->getParamType(i
)));
190 // Clear the lazy arguments bit.
191 const_cast<Function
*>(this)->SubclassData
&= ~1;
194 size_t Function::arg_size() const {
195 return getFunctionType()->getNumParams();
197 bool Function::arg_empty() const {
198 return getFunctionType()->getNumParams() == 0;
201 void Function::setParent(Module
*parent
) {
203 LeakDetector::addGarbageObject(this);
206 LeakDetector::removeGarbageObject(this);
209 // dropAllReferences() - This function causes all the subinstructions to "let
210 // go" of all references that they are maintaining. This allows one to
211 // 'delete' a whole class at a time, even though there may be circular
212 // references... first all references are dropped, and all use counts go to
213 // zero. Then everything is deleted for real. Note that no operations are
214 // valid on an object that has "dropped all references", except operator
217 void Function::dropAllReferences() {
218 for (iterator I
= begin(), E
= end(); I
!= E
; ++I
)
219 I
->dropAllReferences();
220 BasicBlocks
.clear(); // Delete all basic blocks...
223 void Function::addAttribute(unsigned i
, Attributes attr
) {
224 AttrListPtr PAL
= getAttributes();
225 PAL
= PAL
.addAttr(i
, attr
);
229 void Function::removeAttribute(unsigned i
, Attributes attr
) {
230 AttrListPtr PAL
= getAttributes();
231 PAL
= PAL
.removeAttr(i
, attr
);
235 // Maintain the GC name for each function in an on-the-side table. This saves
236 // allocating an additional word in Function for programs which do not use GC
237 // (i.e., most programs) at the cost of increased overhead for clients which do
239 static DenseMap
<const Function
*,PooledStringPtr
> *GCNames
;
240 static StringPool
*GCNamePool
;
241 static ManagedStatic
<sys::SmartRWMutex
<true> > GCLock
;
243 bool Function::hasGC() const {
244 sys::SmartScopedReader
<true> Reader(*GCLock
);
245 return GCNames
&& GCNames
->count(this);
248 const char *Function::getGC() const {
249 assert(hasGC() && "Function has no collector");
250 sys::SmartScopedReader
<true> Reader(*GCLock
);
251 return *(*GCNames
)[this];
254 void Function::setGC(const char *Str
) {
255 sys::SmartScopedWriter
<true> Writer(*GCLock
);
257 GCNamePool
= new StringPool();
259 GCNames
= new DenseMap
<const Function
*,PooledStringPtr
>();
260 (*GCNames
)[this] = GCNamePool
->intern(Str
);
263 void Function::clearGC() {
264 sys::SmartScopedWriter
<true> Writer(*GCLock
);
266 GCNames
->erase(this);
267 if (GCNames
->empty()) {
270 if (GCNamePool
->empty()) {
278 /// copyAttributesFrom - copy all additional attributes (those not needed to
279 /// create a Function) from the Function Src to this one.
280 void Function::copyAttributesFrom(const GlobalValue
*Src
) {
281 assert(isa
<Function
>(Src
) && "Expected a Function!");
282 GlobalValue::copyAttributesFrom(Src
);
283 const Function
*SrcF
= cast
<Function
>(Src
);
284 setCallingConv(SrcF
->getCallingConv());
285 setAttributes(SrcF
->getAttributes());
287 setGC(SrcF
->getGC());
292 /// getIntrinsicID - This method returns the ID number of the specified
293 /// function, or Intrinsic::not_intrinsic if the function is not an
294 /// intrinsic, or if the pointer is null. This value is always defined to be
295 /// zero to allow easy checking for whether a function is intrinsic or not. The
296 /// particular intrinsic functions which correspond to this value are defined in
297 /// llvm/Intrinsics.h.
299 unsigned Function::getIntrinsicID() const {
300 const ValueName
*ValName
= this->getValueName();
303 unsigned Len
= ValName
->getKeyLength();
304 const char *Name
= ValName
->getKeyData();
306 if (Len
< 5 || Name
[4] != '.' || Name
[0] != 'l' || Name
[1] != 'l'
307 || Name
[2] != 'v' || Name
[3] != 'm')
308 return 0; // All intrinsics start with 'llvm.'
310 #define GET_FUNCTION_RECOGNIZER
311 #include "llvm/Intrinsics.gen"
312 #undef GET_FUNCTION_RECOGNIZER
316 std::string
Intrinsic::getName(ID id
, const Type
**Tys
, unsigned numTys
) {
317 assert(id
< num_intrinsics
&& "Invalid intrinsic ID!");
318 const char * const Table
[] = {
320 #define GET_INTRINSIC_NAME_TABLE
321 #include "llvm/Intrinsics.gen"
322 #undef GET_INTRINSIC_NAME_TABLE
326 std::string
Result(Table
[id
]);
327 for (unsigned i
= 0; i
< numTys
; ++i
) {
328 if (const PointerType
* PTyp
= dyn_cast
<PointerType
>(Tys
[i
])) {
329 Result
+= ".p" + llvm::utostr(PTyp
->getAddressSpace()) +
330 EVT::getEVT(PTyp
->getElementType()).getEVTString();
333 Result
+= "." + EVT::getEVT(Tys
[i
]).getEVTString();
338 const FunctionType
*Intrinsic::getType(LLVMContext
&Context
,
339 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(M
->getContext(),
377 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
378 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
379 #include "llvm/Intrinsics.gen"
380 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
382 /// hasAddressTaken - returns true if there are any uses of this function
383 /// other than direct calls or invokes to it.
384 bool Function::hasAddressTaken() const {
385 for (Value::use_const_iterator I
= use_begin(), E
= use_end(); I
!= E
; ++I
) {
386 if (I
.getOperandNo() != 0 ||
387 (!isa
<CallInst
>(*I
) && !isa
<InvokeInst
>(*I
)))