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 llvm::SymbolTableListTraits<Argument, Function>;
33
template class llvm::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 (!getType()->isPointerTy()) 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 (!getType()->isPointerTy()) 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 (!getType()->isPointerTy()) 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 (!getType()->isPointerTy()) 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 (!getType()->isPointerTy()) 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
!getReturnType()->isOpaqueTy() && "invalid return type");
159
SymTab = new ValueSymbolTable();
161
// If the function has arguments, mark them as lazily built.
162
if (Ty->getNumParams())
163
setValueSubclassData(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)->isVoidTy() &&
193
"Cannot have void typed arguments!");
194
ArgumentList.push_back(new Argument(FT->getParamType(i)));
197
// Clear the lazy arguments bit.
198
unsigned SDC = getSubclassDataFromValue();
199
const_cast<Function*>(this)->setValueSubclassData(SDC &= ~1);
202
size_t Function::arg_size() const {
203
return getFunctionType()->getNumParams();
205
bool Function::arg_empty() const {
206
return getFunctionType()->getNumParams() == 0;
209
void Function::setParent(Module *parent) {
211
LeakDetector::addGarbageObject(this);
214
LeakDetector::removeGarbageObject(this);
217
// dropAllReferences() - This function causes all the subinstructions to "let
218
// go" of all references that they are maintaining. This allows one to
219
// 'delete' a whole class at a time, even though there may be circular
220
// references... first all references are dropped, and all use counts go to
221
// zero. Then everything is deleted for real. Note that no operations are
222
// valid on an object that has "dropped all references", except operator
225
void Function::dropAllReferences() {
226
for (iterator I = begin(), E = end(); I != E; ++I)
227
I->dropAllReferences();
229
// Delete all basic blocks.
230
while (!BasicBlocks.empty()) {
231
// If there is still a reference to the block, it must be a 'blockaddress'
232
// constant pointing to it. Just replace the BlockAddress with undef.
233
BasicBlock *BB = BasicBlocks.begin();
234
if (!BB->use_empty()) {
235
BlockAddress *BA = cast<BlockAddress>(BB->use_back());
236
BA->replaceAllUsesWith(UndefValue::get(BA->getType()));
237
BA->destroyConstant();
240
BB->eraseFromParent();
244
void Function::addAttribute(unsigned i, Attributes attr) {
245
AttrListPtr PAL = getAttributes();
246
PAL = PAL.addAttr(i, attr);
250
void Function::removeAttribute(unsigned i, Attributes attr) {
251
AttrListPtr PAL = getAttributes();
252
PAL = PAL.removeAttr(i, attr);
256
// Maintain the GC name for each function in an on-the-side table. This saves
257
// allocating an additional word in Function for programs which do not use GC
258
// (i.e., most programs) at the cost of increased overhead for clients which do
260
static DenseMap<const Function*,PooledStringPtr> *GCNames;
261
static StringPool *GCNamePool;
262
static ManagedStatic<sys::SmartRWMutex<true> > GCLock;
264
bool Function::hasGC() const {
265
sys::SmartScopedReader<true> Reader(*GCLock);
266
return GCNames && GCNames->count(this);
269
const char *Function::getGC() const {
270
assert(hasGC() && "Function has no collector");
271
sys::SmartScopedReader<true> Reader(*GCLock);
272
return *(*GCNames)[this];
275
void Function::setGC(const char *Str) {
276
sys::SmartScopedWriter<true> Writer(*GCLock);
278
GCNamePool = new StringPool();
280
GCNames = new DenseMap<const Function*,PooledStringPtr>();
281
(*GCNames)[this] = GCNamePool->intern(Str);
284
void Function::clearGC() {
285
sys::SmartScopedWriter<true> Writer(*GCLock);
287
GCNames->erase(this);
288
if (GCNames->empty()) {
291
if (GCNamePool->empty()) {
299
/// copyAttributesFrom - copy all additional attributes (those not needed to
300
/// create a Function) from the Function Src to this one.
301
void Function::copyAttributesFrom(const GlobalValue *Src) {
302
assert(isa<Function>(Src) && "Expected a Function!");
303
GlobalValue::copyAttributesFrom(Src);
304
const Function *SrcF = cast<Function>(Src);
305
setCallingConv(SrcF->getCallingConv());
306
setAttributes(SrcF->getAttributes());
308
setGC(SrcF->getGC());
313
/// getIntrinsicID - This method returns the ID number of the specified
314
/// function, or Intrinsic::not_intrinsic if the function is not an
315
/// intrinsic, or if the pointer is null. This value is always defined to be
316
/// zero to allow easy checking for whether a function is intrinsic or not. The
317
/// particular intrinsic functions which correspond to this value are defined in
318
/// llvm/Intrinsics.h.
320
unsigned Function::getIntrinsicID() const {
321
const ValueName *ValName = this->getValueName();
324
unsigned Len = ValName->getKeyLength();
325
const char *Name = ValName->getKeyData();
327
if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
328
|| Name[2] != 'v' || Name[3] != 'm')
329
return 0; // All intrinsics start with 'llvm.'
331
#define GET_FUNCTION_RECOGNIZER
332
#include "llvm/Intrinsics.gen"
333
#undef GET_FUNCTION_RECOGNIZER
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) {
349
if (const PointerType* PTyp = dyn_cast<PointerType>(Tys[i])) {
350
Result += ".p" + llvm::utostr(PTyp->getAddressSpace()) +
351
EVT::getEVT(PTyp->getElementType()).getEVTString();
354
Result += "." + EVT::getEVT(Tys[i]).getEVTString();
359
const FunctionType *Intrinsic::getType(LLVMContext &Context,
360
ID id, const Type **Tys,
362
const Type *ResultTy = NULL;
363
std::vector<const Type*> ArgTys;
364
bool IsVarArg = false;
366
#define GET_INTRINSIC_GENERATOR
367
#include "llvm/Intrinsics.gen"
368
#undef GET_INTRINSIC_GENERATOR
370
return FunctionType::get(ResultTy, ArgTys, IsVarArg);
373
bool Intrinsic::isOverloaded(ID id) {
374
const bool OTable[] = {
376
#define GET_INTRINSIC_OVERLOAD_TABLE
377
#include "llvm/Intrinsics.gen"
378
#undef GET_INTRINSIC_OVERLOAD_TABLE
383
/// This defines the "Intrinsic::getAttributes(ID id)" method.
384
#define GET_INTRINSIC_ATTRIBUTES
385
#include "llvm/Intrinsics.gen"
386
#undef GET_INTRINSIC_ATTRIBUTES
388
Function *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys,
390
// There can never be multiple globals with the same name of different types,
391
// because intrinsics must be a specific type.
393
cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys),
394
getType(M->getContext(),
398
// This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
399
#define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
400
#include "llvm/Intrinsics.gen"
401
#undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
403
/// hasAddressTaken - returns true if there are any uses of this function
404
/// other than direct calls or invokes to it.
405
bool Function::hasAddressTaken() const {
406
for (Value::use_const_iterator I = use_begin(), E = use_end(); I != E; ++I) {
407
if (I.getOperandNo() != 0 ||
408
(!isa<CallInst>(*I) && !isa<InvokeInst>(*I)))