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/CallSite.h"
20 #include "llvm/Support/InstIterator.h"
21 #include "llvm/Support/LeakDetector.h"
22 #include "llvm/Support/ManagedStatic.h"
23 #include "llvm/Support/StringPool.h"
24 #include "llvm/Support/RWMutex.h"
25 #include "llvm/Support/Threading.h"
26 #include "SymbolTableListTraitsImpl.h"
27 #include "llvm/ADT/DenseMap.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/StringExtras.h"
32 // Explicit instantiations of SymbolTableListTraits since some of the methods
33 // are not in the public header file...
34 template class llvm::SymbolTableListTraits<Argument, Function>;
35 template class llvm::SymbolTableListTraits<BasicBlock, Function>;
37 //===----------------------------------------------------------------------===//
38 // Argument Implementation
39 //===----------------------------------------------------------------------===//
41 void Argument::anchor() { }
43 Argument::Argument(Type *Ty, const Twine &Name, Function *Par)
44 : Value(Ty, Value::ArgumentVal) {
47 // Make sure that we get added to a function
48 LeakDetector::addGarbageObject(this);
51 Par->getArgumentList().push_back(this);
55 void Argument::setParent(Function *parent) {
57 LeakDetector::addGarbageObject(this);
60 LeakDetector::removeGarbageObject(this);
63 /// getArgNo - Return the index of this formal argument in its containing
64 /// function. For example in "void foo(int a, float b)" a is 0 and b is 1.
65 unsigned Argument::getArgNo() const {
66 const Function *F = getParent();
67 assert(F && "Argument is not in a function");
69 Function::const_arg_iterator AI = F->arg_begin();
71 for (; &*AI != this; ++AI)
77 /// hasByValAttr - Return true if this argument has the byval attribute on it
78 /// in its containing function.
79 bool Argument::hasByValAttr() const {
80 if (!getType()->isPointerTy()) return false;
81 return getParent()->paramHasAttr(getArgNo()+1, Attribute::ByVal);
84 unsigned Argument::getParamAlignment() const {
85 assert(getType()->isPointerTy() && "Only pointers have alignments");
86 return getParent()->getParamAlignment(getArgNo()+1);
90 /// hasNestAttr - Return true if this argument has the nest attribute on
91 /// it in its containing function.
92 bool Argument::hasNestAttr() const {
93 if (!getType()->isPointerTy()) return false;
94 return getParent()->paramHasAttr(getArgNo()+1, Attribute::Nest);
97 /// hasNoAliasAttr - Return true if this argument has the noalias attribute on
98 /// it in its containing function.
99 bool Argument::hasNoAliasAttr() const {
100 if (!getType()->isPointerTy()) return false;
101 return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoAlias);
104 /// hasNoCaptureAttr - Return true if this argument has the nocapture attribute
105 /// on it in its containing function.
106 bool Argument::hasNoCaptureAttr() const {
107 if (!getType()->isPointerTy()) return false;
108 return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoCapture);
111 /// hasSRetAttr - Return true if this argument has the sret attribute on
112 /// it in its containing function.
113 bool Argument::hasStructRetAttr() const {
114 if (!getType()->isPointerTy()) return false;
115 if (this != getParent()->arg_begin())
116 return false; // StructRet param must be first param
117 return getParent()->paramHasAttr(1, Attribute::StructRet);
120 /// addAttr - Add a Attribute to an argument
121 void Argument::addAttr(Attributes attr) {
122 getParent()->addAttribute(getArgNo() + 1, attr);
125 /// removeAttr - Remove a Attribute from an argument
126 void Argument::removeAttr(Attributes attr) {
127 getParent()->removeAttribute(getArgNo() + 1, attr);
131 //===----------------------------------------------------------------------===//
132 // Helper Methods in Function
133 //===----------------------------------------------------------------------===//
135 LLVMContext &Function::getContext() const {
136 return getType()->getContext();
139 FunctionType *Function::getFunctionType() const {
140 return cast<FunctionType>(getType()->getElementType());
143 bool Function::isVarArg() const {
144 return getFunctionType()->isVarArg();
147 Type *Function::getReturnType() const {
148 return getFunctionType()->getReturnType();
151 void Function::removeFromParent() {
152 getParent()->getFunctionList().remove(this);
155 void Function::eraseFromParent() {
156 getParent()->getFunctionList().erase(this);
159 //===----------------------------------------------------------------------===//
160 // Function Implementation
161 //===----------------------------------------------------------------------===//
163 Function::Function(FunctionType *Ty, LinkageTypes Linkage,
164 const Twine &name, Module *ParentModule)
165 : GlobalValue(PointerType::getUnqual(Ty),
166 Value::FunctionVal, 0, 0, Linkage, name) {
167 assert(FunctionType::isValidReturnType(getReturnType()) &&
168 "invalid return type");
169 SymTab = new ValueSymbolTable();
171 // If the function has arguments, mark them as lazily built.
172 if (Ty->getNumParams())
173 setValueSubclassData(1); // Set the "has lazy arguments" bit.
175 // Make sure that we get added to a function
176 LeakDetector::addGarbageObject(this);
179 ParentModule->getFunctionList().push_back(this);
181 // Ensure intrinsics have the right parameter attributes.
182 if (unsigned IID = getIntrinsicID())
183 setAttributes(Intrinsic::getAttributes(Intrinsic::ID(IID)));
187 Function::~Function() {
188 dropAllReferences(); // After this it is safe to delete instructions.
190 // Delete all of the method arguments and unlink from symbol table...
191 ArgumentList.clear();
194 // Remove the function from the on-the-side GC table.
198 void Function::BuildLazyArguments() const {
199 // Create the arguments vector, all arguments start out unnamed.
200 FunctionType *FT = getFunctionType();
201 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
202 assert(!FT->getParamType(i)->isVoidTy() &&
203 "Cannot have void typed arguments!");
204 ArgumentList.push_back(new Argument(FT->getParamType(i)));
207 // Clear the lazy arguments bit.
208 unsigned SDC = getSubclassDataFromValue();
209 const_cast<Function*>(this)->setValueSubclassData(SDC &= ~1);
212 size_t Function::arg_size() const {
213 return getFunctionType()->getNumParams();
215 bool Function::arg_empty() const {
216 return getFunctionType()->getNumParams() == 0;
219 void Function::setParent(Module *parent) {
221 LeakDetector::addGarbageObject(this);
224 LeakDetector::removeGarbageObject(this);
227 // dropAllReferences() - This function causes all the subinstructions to "let
228 // go" of all references that they are maintaining. This allows one to
229 // 'delete' a whole class at a time, even though there may be circular
230 // references... first all references are dropped, and all use counts go to
231 // zero. Then everything is deleted for real. Note that no operations are
232 // valid on an object that has "dropped all references", except operator
235 void Function::dropAllReferences() {
236 for (iterator I = begin(), E = end(); I != E; ++I)
237 I->dropAllReferences();
239 // Delete all basic blocks. They are now unused, except possibly by
240 // blockaddresses, but BasicBlock's destructor takes care of those.
241 while (!BasicBlocks.empty())
242 BasicBlocks.begin()->eraseFromParent();
245 void Function::addAttribute(unsigned i, Attributes attr) {
246 AttrListPtr PAL = getAttributes();
247 PAL = PAL.addAttr(i, attr);
251 void Function::removeAttribute(unsigned i, Attributes attr) {
252 AttrListPtr PAL = getAttributes();
253 PAL = PAL.removeAttr(i, attr);
257 // Maintain the GC name for each function in an on-the-side table. This saves
258 // allocating an additional word in Function for programs which do not use GC
259 // (i.e., most programs) at the cost of increased overhead for clients which do
261 static DenseMap<const Function*,PooledStringPtr> *GCNames;
262 static StringPool *GCNamePool;
263 static ManagedStatic<sys::SmartRWMutex<true> > GCLock;
265 bool Function::hasGC() const {
266 sys::SmartScopedReader<true> Reader(*GCLock);
267 return GCNames && GCNames->count(this);
270 const char *Function::getGC() const {
271 assert(hasGC() && "Function has no collector");
272 sys::SmartScopedReader<true> Reader(*GCLock);
273 return *(*GCNames)[this];
276 void Function::setGC(const char *Str) {
277 sys::SmartScopedWriter<true> Writer(*GCLock);
279 GCNamePool = new StringPool();
281 GCNames = new DenseMap<const Function*,PooledStringPtr>();
282 (*GCNames)[this] = GCNamePool->intern(Str);
285 void Function::clearGC() {
286 sys::SmartScopedWriter<true> Writer(*GCLock);
288 GCNames->erase(this);
289 if (GCNames->empty()) {
292 if (GCNamePool->empty()) {
300 /// copyAttributesFrom - copy all additional attributes (those not needed to
301 /// create a Function) from the Function Src to this one.
302 void Function::copyAttributesFrom(const GlobalValue *Src) {
303 assert(isa<Function>(Src) && "Expected a Function!");
304 GlobalValue::copyAttributesFrom(Src);
305 const Function *SrcF = cast<Function>(Src);
306 setCallingConv(SrcF->getCallingConv());
307 setAttributes(SrcF->getAttributes());
309 setGC(SrcF->getGC());
314 /// getIntrinsicID - This method returns the ID number of the specified
315 /// function, or Intrinsic::not_intrinsic if the function is not an
316 /// intrinsic, or if the pointer is null. This value is always defined to be
317 /// zero to allow easy checking for whether a function is intrinsic or not. The
318 /// particular intrinsic functions which correspond to this value are defined in
319 /// llvm/Intrinsics.h.
321 unsigned Function::getIntrinsicID() const {
322 const ValueName *ValName = this->getValueName();
325 unsigned Len = ValName->getKeyLength();
326 const char *Name = ValName->getKeyData();
328 if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
329 || Name[2] != 'v' || Name[3] != 'm')
330 return 0; // All intrinsics start with 'llvm.'
332 #define GET_FUNCTION_RECOGNIZER
333 #include "llvm/Intrinsics.gen"
334 #undef GET_FUNCTION_RECOGNIZER
338 std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) {
339 assert(id < num_intrinsics && "Invalid intrinsic ID!");
340 static const char * const Table[] = {
342 #define GET_INTRINSIC_NAME_TABLE
343 #include "llvm/Intrinsics.gen"
344 #undef GET_INTRINSIC_NAME_TABLE
348 std::string Result(Table[id]);
349 for (unsigned i = 0; i < Tys.size(); ++i) {
350 if (PointerType* PTyp = dyn_cast<PointerType>(Tys[i])) {
351 Result += ".p" + llvm::utostr(PTyp->getAddressSpace()) +
352 EVT::getEVT(PTyp->getElementType()).getEVTString();
355 Result += "." + EVT::getEVT(Tys[i]).getEVTString();
360 #define GET_INTRINSTIC_GENERATOR_GLOBAL
361 #include "llvm/Intrinsics.gen"
362 #undef GET_INTRINSTIC_GENERATOR_GLOBAL
364 static Type *DecodeFixedType(unsigned &TableVal, LLVMContext &Context) {
365 unsigned Nibble = TableVal & 0xF;
368 switch ((IIT_Info)Nibble) {
369 case IIT_Done: return Type::getVoidTy(Context);
370 case IIT_I1: return Type::getInt1Ty(Context);
371 case IIT_I8: return Type::getInt8Ty(Context);
372 case IIT_I16: return Type::getInt16Ty(Context);
373 case IIT_I32: return Type::getInt32Ty(Context);
374 case IIT_I64: return Type::getInt64Ty(Context);
375 case IIT_F32: return Type::getFloatTy(Context);
376 case IIT_F64: return Type::getDoubleTy(Context);
377 case IIT_V2: return VectorType::get(DecodeFixedType(TableVal, Context), 2);
378 case IIT_V4: return VectorType::get(DecodeFixedType(TableVal, Context), 4);
379 case IIT_V8: return VectorType::get(DecodeFixedType(TableVal, Context), 8);
380 case IIT_V16: return VectorType::get(DecodeFixedType(TableVal, Context), 16);
381 case IIT_MMX: return Type::getX86_MMXTy(Context);
382 case IIT_PTR: return PointerType::get(DecodeFixedType(TableVal, Context),0);
383 case IIT_ARG: assert(0 && "Unimp!");
385 llvm_unreachable("unhandled");
389 FunctionType *Intrinsic::getType(LLVMContext &Context,
390 ID id, ArrayRef<Type*> Tys) {
392 SmallVector<Type*, 8> ArgTys;
394 // Check to see if the intrinsic's type was expressible by the table.
395 unsigned TableVal = IIT_Table[id-1];
396 if (TableVal != ~0U) {
397 ResultTy = DecodeFixedType(TableVal, Context);
400 ArgTys.push_back(DecodeFixedType(TableVal, Context));
402 return FunctionType::get(ResultTy, ArgTys, false);
406 #define GET_INTRINSIC_GENERATOR
407 #include "llvm/Intrinsics.gen"
408 #undef GET_INTRINSIC_GENERATOR
410 return FunctionType::get(ResultTy, ArgTys, false);
413 bool Intrinsic::isOverloaded(ID id) {
414 #define GET_INTRINSIC_OVERLOAD_TABLE
415 #include "llvm/Intrinsics.gen"
416 #undef GET_INTRINSIC_OVERLOAD_TABLE
419 /// This defines the "Intrinsic::getAttributes(ID id)" method.
420 #define GET_INTRINSIC_ATTRIBUTES
421 #include "llvm/Intrinsics.gen"
422 #undef GET_INTRINSIC_ATTRIBUTES
424 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
425 // There can never be multiple globals with the same name of different types,
426 // because intrinsics must be a specific type.
428 cast<Function>(M->getOrInsertFunction(getName(id, Tys),
429 getType(M->getContext(), id, Tys)));
432 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
433 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
434 #include "llvm/Intrinsics.gen"
435 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
437 /// hasAddressTaken - returns true if there are any uses of this function
438 /// other than direct calls or invokes to it.
439 bool Function::hasAddressTaken(const User* *PutOffender) const {
440 for (Value::const_use_iterator I = use_begin(), E = use_end(); I != E; ++I) {
442 if (isa<BlockAddress>(U))
444 if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
445 return PutOffender ? (*PutOffender = U, true) : true;
446 ImmutableCallSite CS(cast<Instruction>(U));
448 return PutOffender ? (*PutOffender = U, true) : true;
453 bool Function::isDefTriviallyDead() const {
455 if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
456 !hasAvailableExternallyLinkage())
459 // Check if the function is used by anything other than a blockaddress.
460 for (Value::const_use_iterator I = use_begin(), E = use_end(); I != E; ++I)
461 if (!isa<BlockAddress>(*I))
467 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
468 /// setjmp or other function that gcc recognizes as "returning twice".
469 bool Function::callsFunctionThatReturnsTwice() const {
470 for (const_inst_iterator
471 I = inst_begin(this), E = inst_end(this); I != E; ++I) {
472 const CallInst* callInst = dyn_cast<CallInst>(&*I);
475 if (callInst->canReturnTwice())