Silence -Wunused-variable in release builds.
[llvm/stm8.git] / lib / VMCore / Function.cpp
blob972319e7402f90f7ca9df91ac020990e01059a3a
1 //===-- Function.cpp - Implement the Global object classes ----------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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/LeakDetector.h"
21 #include "llvm/Support/ManagedStatic.h"
22 #include "llvm/Support/StringPool.h"
23 #include "llvm/Support/RWMutex.h"
24 #include "llvm/Support/Threading.h"
25 #include "SymbolTableListTraitsImpl.h"
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/StringExtras.h"
29 using namespace llvm;
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 Argument::Argument(const Type *Ty, const Twine &Name, Function *Par)
42 : Value(Ty, Value::ArgumentVal) {
43 Parent = 0;
45 // Make sure that we get added to a function
46 LeakDetector::addGarbageObject(this);
48 if (Par)
49 Par->getArgumentList().push_back(this);
50 setName(Name);
53 void Argument::setParent(Function *parent) {
54 if (getParent())
55 LeakDetector::addGarbageObject(this);
56 Parent = parent;
57 if (getParent())
58 LeakDetector::removeGarbageObject(this);
61 /// getArgNo - Return the index of this formal argument in its containing
62 /// function. For example in "void foo(int a, float b)" a is 0 and b is 1.
63 unsigned Argument::getArgNo() const {
64 const Function *F = getParent();
65 assert(F && "Argument is not in a function");
67 Function::const_arg_iterator AI = F->arg_begin();
68 unsigned ArgIdx = 0;
69 for (; &*AI != this; ++AI)
70 ++ArgIdx;
72 return ArgIdx;
75 /// hasByValAttr - Return true if this argument has the byval attribute on it
76 /// in its containing function.
77 bool Argument::hasByValAttr() const {
78 if (!getType()->isPointerTy()) return false;
79 return getParent()->paramHasAttr(getArgNo()+1, Attribute::ByVal);
82 unsigned Argument::getParamAlignment() const {
83 assert(getType()->isPointerTy() && "Only pointers have alignments");
84 return getParent()->getParamAlignment(getArgNo()+1);
88 /// hasNestAttr - Return true if this argument has the nest attribute on
89 /// it in its containing function.
90 bool Argument::hasNestAttr() const {
91 if (!getType()->isPointerTy()) return false;
92 return getParent()->paramHasAttr(getArgNo()+1, Attribute::Nest);
95 /// hasNoAliasAttr - Return true if this argument has the noalias attribute on
96 /// it in its containing function.
97 bool Argument::hasNoAliasAttr() const {
98 if (!getType()->isPointerTy()) return false;
99 return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoAlias);
102 /// hasNoCaptureAttr - Return true if this argument has the nocapture attribute
103 /// on it in its containing function.
104 bool Argument::hasNoCaptureAttr() const {
105 if (!getType()->isPointerTy()) return false;
106 return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoCapture);
109 /// hasSRetAttr - Return true if this argument has the sret attribute on
110 /// it in its containing function.
111 bool Argument::hasStructRetAttr() const {
112 if (!getType()->isPointerTy()) return false;
113 if (this != getParent()->arg_begin())
114 return false; // StructRet param must be first param
115 return getParent()->paramHasAttr(1, Attribute::StructRet);
118 /// addAttr - Add a Attribute to an argument
119 void Argument::addAttr(Attributes attr) {
120 getParent()->addAttribute(getArgNo() + 1, attr);
123 /// removeAttr - Remove a Attribute from an argument
124 void Argument::removeAttr(Attributes attr) {
125 getParent()->removeAttribute(getArgNo() + 1, attr);
129 //===----------------------------------------------------------------------===//
130 // Helper Methods in Function
131 //===----------------------------------------------------------------------===//
133 LLVMContext &Function::getContext() const {
134 return getType()->getContext();
137 FunctionType *Function::getFunctionType() const {
138 return cast<FunctionType>(getType()->getElementType());
141 bool Function::isVarArg() const {
142 return getFunctionType()->isVarArg();
145 Type *Function::getReturnType() const {
146 return getFunctionType()->getReturnType();
149 void Function::removeFromParent() {
150 getParent()->getFunctionList().remove(this);
153 void Function::eraseFromParent() {
154 getParent()->getFunctionList().erase(this);
157 //===----------------------------------------------------------------------===//
158 // Function Implementation
159 //===----------------------------------------------------------------------===//
161 Function::Function(const FunctionType *Ty, LinkageTypes Linkage,
162 const Twine &name, Module *ParentModule)
163 : GlobalValue(PointerType::getUnqual(Ty),
164 Value::FunctionVal, 0, 0, Linkage, name) {
165 assert(FunctionType::isValidReturnType(getReturnType()) &&
166 "invalid return type");
167 SymTab = new ValueSymbolTable();
169 // If the function has arguments, mark them as lazily built.
170 if (Ty->getNumParams())
171 setValueSubclassData(1); // Set the "has lazy arguments" bit.
173 // Make sure that we get added to a function
174 LeakDetector::addGarbageObject(this);
176 if (ParentModule)
177 ParentModule->getFunctionList().push_back(this);
179 // Ensure intrinsics have the right parameter attributes.
180 if (unsigned IID = getIntrinsicID())
181 setAttributes(Intrinsic::getAttributes(Intrinsic::ID(IID)));
185 Function::~Function() {
186 dropAllReferences(); // After this it is safe to delete instructions.
188 // Delete all of the method arguments and unlink from symbol table...
189 ArgumentList.clear();
190 delete SymTab;
192 // Remove the function from the on-the-side GC table.
193 clearGC();
196 void Function::BuildLazyArguments() const {
197 // Create the arguments vector, all arguments start out unnamed.
198 const FunctionType *FT = getFunctionType();
199 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
200 assert(!FT->getParamType(i)->isVoidTy() &&
201 "Cannot have void typed arguments!");
202 ArgumentList.push_back(new Argument(FT->getParamType(i)));
205 // Clear the lazy arguments bit.
206 unsigned SDC = getSubclassDataFromValue();
207 const_cast<Function*>(this)->setValueSubclassData(SDC &= ~1);
210 size_t Function::arg_size() const {
211 return getFunctionType()->getNumParams();
213 bool Function::arg_empty() const {
214 return getFunctionType()->getNumParams() == 0;
217 void Function::setParent(Module *parent) {
218 if (getParent())
219 LeakDetector::addGarbageObject(this);
220 Parent = parent;
221 if (getParent())
222 LeakDetector::removeGarbageObject(this);
225 // dropAllReferences() - This function causes all the subinstructions to "let
226 // go" of all references that they are maintaining. This allows one to
227 // 'delete' a whole class at a time, even though there may be circular
228 // references... first all references are dropped, and all use counts go to
229 // zero. Then everything is deleted for real. Note that no operations are
230 // valid on an object that has "dropped all references", except operator
231 // delete.
233 void Function::dropAllReferences() {
234 for (iterator I = begin(), E = end(); I != E; ++I)
235 I->dropAllReferences();
237 // Delete all basic blocks. They are now unused, except possibly by
238 // blockaddresses, but BasicBlock's destructor takes care of those.
239 while (!BasicBlocks.empty())
240 BasicBlocks.begin()->eraseFromParent();
243 void Function::addAttribute(unsigned i, Attributes attr) {
244 AttrListPtr PAL = getAttributes();
245 PAL = PAL.addAttr(i, attr);
246 setAttributes(PAL);
249 void Function::removeAttribute(unsigned i, Attributes attr) {
250 AttrListPtr PAL = getAttributes();
251 PAL = PAL.removeAttr(i, attr);
252 setAttributes(PAL);
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
258 // use GC.
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);
276 if (!GCNamePool)
277 GCNamePool = new StringPool();
278 if (!GCNames)
279 GCNames = new DenseMap<const Function*,PooledStringPtr>();
280 (*GCNames)[this] = GCNamePool->intern(Str);
283 void Function::clearGC() {
284 sys::SmartScopedWriter<true> Writer(*GCLock);
285 if (GCNames) {
286 GCNames->erase(this);
287 if (GCNames->empty()) {
288 delete GCNames;
289 GCNames = 0;
290 if (GCNamePool->empty()) {
291 delete GCNamePool;
292 GCNamePool = 0;
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());
306 if (SrcF->hasGC())
307 setGC(SrcF->getGC());
308 else
309 clearGC();
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();
321 if (!ValName)
322 return 0;
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
333 return 0;
336 std::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) {
337 assert(id < num_intrinsics && "Invalid intrinsic ID!");
338 static const char * const Table[] = {
339 "not_intrinsic",
340 #define GET_INTRINSIC_NAME_TABLE
341 #include "llvm/Intrinsics.gen"
342 #undef GET_INTRINSIC_NAME_TABLE
344 if (numTys == 0)
345 return Table[id];
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();
352 else if (Tys[i])
353 Result += "." + EVT::getEVT(Tys[i]).getEVTString();
355 return Result;
358 const FunctionType *Intrinsic::getType(LLVMContext &Context,
359 ID id, const Type **Tys,
360 unsigned numTys) {
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 static const bool OTable[] = {
374 false,
375 #define GET_INTRINSIC_OVERLOAD_TABLE
376 #include "llvm/Intrinsics.gen"
377 #undef GET_INTRINSIC_OVERLOAD_TABLE
379 return OTable[id];
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,
388 unsigned numTys) {
389 // There can never be multiple globals with the same name of different types,
390 // because intrinsics must be a specific type.
391 return
392 cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys),
393 getType(M->getContext(),
394 id, Tys, numTys)));
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 User* *PutOffender) const {
405 for (Value::const_use_iterator I = use_begin(), E = use_end(); I != E; ++I) {
406 const User *U = *I;
407 if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
408 return PutOffender ? (*PutOffender = U, true) : true;
409 ImmutableCallSite CS(cast<Instruction>(U));
410 if (!CS.isCallee(I))
411 return PutOffender ? (*PutOffender = U, true) : true;
413 return false;
416 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
417 /// setjmp or other function that gcc recognizes as "returning twice".
419 /// FIXME: Remove after <rdar://problem/8031714> is fixed.
420 /// FIXME: Is the above FIXME valid?
421 bool Function::callsFunctionThatReturnsTwice() const {
422 const Module *M = this->getParent();
423 static const char *ReturnsTwiceFns[] = {
424 "_setjmp",
425 "setjmp",
426 "sigsetjmp",
427 "setjmp_syscall",
428 "savectx",
429 "qsetjmp",
430 "vfork",
431 "getcontext"
434 for (unsigned I = 0; I < array_lengthof(ReturnsTwiceFns); ++I)
435 if (const Function *Callee = M->getFunction(ReturnsTwiceFns[I])) {
436 if (!Callee->use_empty())
437 for (Value::const_use_iterator
438 I = Callee->use_begin(), E = Callee->use_end();
439 I != E; ++I)
440 if (const CallInst *CI = dyn_cast<CallInst>(*I))
441 if (CI->getParent()->getParent() == this)
442 return true;
445 return false;
448 // vim: sw=2 ai