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/StringPool.h"
20 #include "SymbolTableListTraitsImpl.h"
21 #include "llvm/ADT/BitVector.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/StringExtras.h"
26 BasicBlock *ilist_traits<BasicBlock>::createSentinel() {
27 BasicBlock *Ret = BasicBlock::Create();
28 // This should not be garbage monitored.
29 LeakDetector::removeGarbageObject(Ret);
33 iplist<BasicBlock> &ilist_traits<BasicBlock>::getList(Function *F) {
34 return F->getBasicBlockList();
37 Argument *ilist_traits<Argument>::createSentinel() {
38 Argument *Ret = new Argument(Type::Int32Ty);
39 // This should not be garbage monitored.
40 LeakDetector::removeGarbageObject(Ret);
44 iplist<Argument> &ilist_traits<Argument>::getList(Function *F) {
45 return F->getArgumentList();
48 // Explicit instantiations of SymbolTableListTraits since some of the methods
49 // are not in the public header file...
50 template class SymbolTableListTraits<Argument, Function>;
51 template class SymbolTableListTraits<BasicBlock, Function>;
53 //===----------------------------------------------------------------------===//
54 // Argument Implementation
55 //===----------------------------------------------------------------------===//
57 Argument::Argument(const Type *Ty, const std::string &Name, Function *Par)
58 : Value(Ty, Value::ArgumentVal) {
61 // Make sure that we get added to a function
62 LeakDetector::addGarbageObject(this);
65 Par->getArgumentList().push_back(this);
69 void Argument::setParent(Function *parent) {
71 LeakDetector::addGarbageObject(this);
74 LeakDetector::removeGarbageObject(this);
77 /// getArgNo - Return the index of this formal argument in its containing
78 /// function. For example in "void foo(int a, float b)" a is 0 and b is 1.
79 unsigned Argument::getArgNo() const {
80 const Function *F = getParent();
81 assert(F && "Argument is not in a function");
83 Function::const_arg_iterator AI = F->arg_begin();
85 for (; &*AI != this; ++AI)
91 /// hasByValAttr - Return true if this argument has the byval attribute on it
92 /// in its containing function.
93 bool Argument::hasByValAttr() const {
94 if (!isa<PointerType>(getType())) return false;
95 return getParent()->paramHasAttr(getArgNo()+1, Attribute::ByVal);
98 /// hasNoAliasAttr - Return true if this argument has the noalias attribute on
99 /// it in its containing function.
100 bool Argument::hasNoAliasAttr() const {
101 if (!isa<PointerType>(getType())) return false;
102 return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoAlias);
105 /// hasNoCaptureAttr - Return true if this argument has the nocapture attribute
106 /// on it in its containing function.
107 bool Argument::hasNoCaptureAttr() const {
108 if (!isa<PointerType>(getType())) return false;
109 return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoCapture);
112 /// hasSRetAttr - Return true if this argument has the sret attribute on
113 /// it in its containing function.
114 bool Argument::hasStructRetAttr() const {
115 if (!isa<PointerType>(getType())) return false;
116 if (this != getParent()->arg_begin())
117 return false; // StructRet param must be first param
118 return getParent()->paramHasAttr(1, Attribute::StructRet);
121 /// addAttr - Add a Attribute to an argument
122 void Argument::addAttr(Attributes attr) {
123 getParent()->addAttribute(getArgNo() + 1, attr);
126 /// removeAttr - Remove a Attribute from an argument
127 void Argument::removeAttr(Attributes attr) {
128 getParent()->removeAttribute(getArgNo() + 1, attr);
132 //===----------------------------------------------------------------------===//
133 // Helper Methods in Function
134 //===----------------------------------------------------------------------===//
136 const FunctionType *Function::getFunctionType() const {
137 return cast<FunctionType>(getType()->getElementType());
140 bool Function::isVarArg() const {
141 return getFunctionType()->isVarArg();
144 const Type *Function::getReturnType() const {
145 return getFunctionType()->getReturnType();
148 void Function::removeFromParent() {
149 getParent()->getFunctionList().remove(this);
152 void Function::eraseFromParent() {
153 getParent()->getFunctionList().erase(this);
156 //===----------------------------------------------------------------------===//
157 // Function Implementation
158 //===----------------------------------------------------------------------===//
160 Function::Function(const FunctionType *Ty, LinkageTypes Linkage,
161 const std::string &name, Module *ParentModule)
162 : GlobalValue(PointerType::getUnqual(Ty),
163 Value::FunctionVal, 0, 0, Linkage, name) {
164 SymTab = new ValueSymbolTable();
166 assert((getReturnType()->isFirstClassType() ||getReturnType() == Type::VoidTy
167 || isa<StructType>(getReturnType()))
168 && "LLVM functions cannot return aggregate values!");
170 // If the function has arguments, mark them as lazily built.
171 if (Ty->getNumParams())
172 SubclassData = 1; // Set the "has lazy arguments" bit.
174 // Make sure that we get added to a function
175 LeakDetector::addGarbageObject(this);
178 ParentModule->getFunctionList().push_back(this);
180 // Ensure intrinsics have the right parameter attributes.
181 if (unsigned IID = getIntrinsicID(true))
182 setAttributes(Intrinsic::getAttributes(Intrinsic::ID(IID)));
186 Function::~Function() {
187 dropAllReferences(); // After this it is safe to delete instructions.
189 // Delete all of the method arguments and unlink from symbol table...
190 ArgumentList.clear();
193 // Remove the function from the on-the-side GC table.
197 void Function::BuildLazyArguments() const {
198 // Create the arguments vector, all arguments start out unnamed.
199 const FunctionType *FT = getFunctionType();
200 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
201 assert(FT->getParamType(i) != Type::VoidTy &&
202 "Cannot have void typed arguments!");
203 ArgumentList.push_back(new Argument(FT->getParamType(i)));
206 // Clear the lazy arguments bit.
207 const_cast<Function*>(this)->SubclassData &= ~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) {
219 LeakDetector::addGarbageObject(this);
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
233 void Function::dropAllReferences() {
234 for (iterator I = begin(), E = end(); I != E; ++I)
235 I->dropAllReferences();
236 BasicBlocks.clear(); // Delete all basic blocks...
239 void Function::addAttribute(unsigned i, Attributes attr) {
240 AttrListPtr PAL = getAttributes();
241 PAL = PAL.addAttr(i, attr);
245 void Function::removeAttribute(unsigned i, Attributes attr) {
246 AttrListPtr PAL = getAttributes();
247 PAL = PAL.removeAttr(i, attr);
251 // Maintain the GC name for each function in an on-the-side table. This saves
252 // allocating an additional word in Function for programs which do not use GC
253 // (i.e., most programs) at the cost of increased overhead for clients which do
255 static DenseMap<const Function*,PooledStringPtr> *GCNames;
256 static StringPool *GCNamePool;
258 bool Function::hasGC() const {
259 return GCNames && GCNames->count(this);
262 const char *Function::getGC() const {
263 assert(hasGC() && "Function has no collector");
264 return *(*GCNames)[this];
267 void Function::setGC(const char *Str) {
269 GCNamePool = new StringPool();
271 GCNames = new DenseMap<const Function*,PooledStringPtr>();
272 (*GCNames)[this] = GCNamePool->intern(Str);
275 void Function::clearGC() {
277 GCNames->erase(this);
278 if (GCNames->empty()) {
281 if (GCNamePool->empty()) {
289 /// copyAttributesFrom - copy all additional attributes (those not needed to
290 /// create a Function) from the Function Src to this one.
291 void Function::copyAttributesFrom(const GlobalValue *Src) {
292 assert(isa<Function>(Src) && "Expected a Function!");
293 GlobalValue::copyAttributesFrom(Src);
294 const Function *SrcF = cast<Function>(Src);
295 setCallingConv(SrcF->getCallingConv());
296 setAttributes(SrcF->getAttributes());
298 setGC(SrcF->getGC());
303 /// getIntrinsicID - This method returns the ID number of the specified
304 /// function, or Intrinsic::not_intrinsic if the function is not an
305 /// intrinsic, or if the pointer is null. This value is always defined to be
306 /// zero to allow easy checking for whether a function is intrinsic or not. The
307 /// particular intrinsic functions which correspond to this value are defined in
308 /// llvm/Intrinsics.h.
310 unsigned Function::getIntrinsicID(bool noAssert) const {
311 const ValueName *ValName = this->getValueName();
314 unsigned Len = ValName->getKeyLength();
315 const char *Name = ValName->getKeyData();
317 if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
318 || Name[2] != 'v' || Name[3] != 'm')
319 return 0; // All intrinsics start with 'llvm.'
321 assert((Len != 5 || noAssert) && "'llvm.' is an invalid intrinsic name!");
323 #define GET_FUNCTION_RECOGNIZER
324 #include "llvm/Intrinsics.gen"
325 #undef GET_FUNCTION_RECOGNIZER
326 assert(noAssert && "Invalid LLVM intrinsic name");
330 std::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) {
331 assert(id < num_intrinsics && "Invalid intrinsic ID!");
332 const char * const Table[] = {
334 #define GET_INTRINSIC_NAME_TABLE
335 #include "llvm/Intrinsics.gen"
336 #undef GET_INTRINSIC_NAME_TABLE
340 std::string Result(Table[id]);
341 for (unsigned i = 0; i < numTys; ++i) {
342 if (const PointerType* PTyp = dyn_cast<PointerType>(Tys[i])) {
343 Result += ".p" + llvm::utostr(PTyp->getAddressSpace()) +
344 MVT::getMVT(PTyp->getElementType()).getMVTString();
347 Result += "." + MVT::getMVT(Tys[i]).getMVTString();
352 const FunctionType *Intrinsic::getType(ID id, const Type **Tys,
354 const Type *ResultTy = NULL;
355 std::vector<const Type*> ArgTys;
356 bool IsVarArg = false;
358 #define GET_INTRINSIC_GENERATOR
359 #include "llvm/Intrinsics.gen"
360 #undef GET_INTRINSIC_GENERATOR
362 return FunctionType::get(ResultTy, ArgTys, IsVarArg);
365 AttrListPtr Intrinsic::getAttributes(ID id) {
366 Attributes Attr = Attribute::None;
368 #define GET_INTRINSIC_ATTRIBUTES
369 #include "llvm/Intrinsics.gen"
370 #undef GET_INTRINSIC_ATTRIBUTES
372 // Intrinsics cannot throw exceptions.
373 Attr |= Attribute::NoUnwind;
375 AttributeWithIndex PAWI = AttributeWithIndex::get(~0, Attr);
376 return AttrListPtr::get(&PAWI, 1);
379 Function *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys,
381 // There can never be multiple globals with the same name of different types,
382 // because intrinsics must be a specific type.
384 cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys),
385 getType(id, Tys, numTys)));