1 //===-- Function.cpp - Implement the Global object classes ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/ManagedStatic.h"
20 #include "SymbolTableListTraitsImpl.h"
21 #include "llvm/ADT/StringExtras.h"
24 BasicBlock *ilist_traits<BasicBlock>::createSentinel() {
25 BasicBlock *Ret = new BasicBlock();
26 // This should not be garbage monitored.
27 LeakDetector::removeGarbageObject(Ret);
31 iplist<BasicBlock> &ilist_traits<BasicBlock>::getList(Function *F) {
32 return F->getBasicBlockList();
35 Argument *ilist_traits<Argument>::createSentinel() {
36 Argument *Ret = new Argument(Type::Int32Ty);
37 // This should not be garbage monitored.
38 LeakDetector::removeGarbageObject(Ret);
42 iplist<Argument> &ilist_traits<Argument>::getList(Function *F) {
43 return F->getArgumentList();
46 // Explicit instantiations of SymbolTableListTraits since some of the methods
47 // are not in the public header file...
48 template class SymbolTableListTraits<Argument, Function>;
49 template class SymbolTableListTraits<BasicBlock, Function>;
51 //===----------------------------------------------------------------------===//
52 // Argument Implementation
53 //===----------------------------------------------------------------------===//
55 Argument::Argument(const Type *Ty, const std::string &Name, Function *Par)
56 : Value(Ty, Value::ArgumentVal) {
59 // Make sure that we get added to a function
60 LeakDetector::addGarbageObject(this);
63 Par->getArgumentList().push_back(this);
67 void Argument::setParent(Function *parent) {
69 LeakDetector::addGarbageObject(this);
72 LeakDetector::removeGarbageObject(this);
75 //===----------------------------------------------------------------------===//
76 // ParamAttrsList Implementation
77 //===----------------------------------------------------------------------===//
80 ParamAttrsList::getParamAttrs(uint16_t Index) const {
81 unsigned limit = attrs.size();
82 for (unsigned i = 0; i < limit; ++i)
83 if (attrs[i].index == Index)
84 return attrs[i].attrs;
85 return ParamAttr::None;
89 ParamAttrsList::getParamAttrsText(uint16_t Attrs) {
91 if (Attrs & ParamAttr::ZExt)
93 if (Attrs & ParamAttr::SExt)
95 if (Attrs & ParamAttr::NoReturn)
96 Result += "noreturn ";
97 if (Attrs & ParamAttr::NoUnwind)
98 Result += "nounwind ";
99 if (Attrs & ParamAttr::InReg)
101 if (Attrs & ParamAttr::NoAlias)
102 Result += "noalias ";
103 if (Attrs & ParamAttr::StructRet)
105 if (Attrs & ParamAttr::ByVal)
107 if (Attrs & ParamAttr::Nest)
109 if (Attrs & ParamAttr::ReadNone)
110 Result += "readnone ";
111 if (Attrs & ParamAttr::ReadOnly)
112 Result += "readonly ";
116 /// onlyInformative - Returns whether only informative attributes are set.
117 static inline bool onlyInformative(uint16_t attrs) {
118 return !(attrs & ~ParamAttr::Informative);
122 ParamAttrsList::areCompatible(const ParamAttrsList *A, const ParamAttrsList *B){
125 unsigned ASize = A ? A->size() : 0;
126 unsigned BSize = B ? B->size() : 0;
130 while (AIndex < ASize && BIndex < BSize) {
131 uint16_t AIdx = A->getParamIndex(AIndex);
132 uint16_t BIdx = B->getParamIndex(BIndex);
133 uint16_t AAttrs = A->getParamAttrsAtIndex(AIndex);
134 uint16_t BAttrs = B->getParamAttrsAtIndex(AIndex);
137 if (!onlyInformative(AAttrs))
140 } else if (BIdx < AIdx) {
141 if (!onlyInformative(BAttrs))
145 if (!onlyInformative(AAttrs ^ BAttrs))
151 for (; AIndex < ASize; ++AIndex)
152 if (!onlyInformative(A->getParamAttrsAtIndex(AIndex)))
154 for (; BIndex < BSize; ++BIndex)
155 if (!onlyInformative(B->getParamAttrsAtIndex(AIndex)))
161 ParamAttrsList::Profile(FoldingSetNodeID &ID) const {
162 for (unsigned i = 0; i < attrs.size(); ++i) {
163 uint32_t val = uint32_t(attrs[i].attrs) << 16 | attrs[i].index;
168 static ManagedStatic<FoldingSet<ParamAttrsList> > ParamAttrsLists;
171 ParamAttrsList::get(const ParamAttrsVector &attrVec) {
172 // If there are no attributes then return a null ParamAttrsList pointer.
177 for (unsigned i = 0, e = attrVec.size(); i < e; ++i) {
178 assert(attrVec[i].attrs != ParamAttr::None
179 && "Pointless parameter attribute!");
180 assert((!i || attrVec[i-1].index < attrVec[i].index)
181 && "Misordered ParamAttrsList!");
185 // Otherwise, build a key to look up the existing attributes.
186 ParamAttrsList key(attrVec);
190 ParamAttrsList* PAL = ParamAttrsLists->FindNodeOrInsertPos(ID, InsertPos);
192 // If we didn't find any existing attributes of the same shape then
193 // create a new one and insert it.
195 PAL = new ParamAttrsList(attrVec);
196 ParamAttrsLists->InsertNode(PAL, InsertPos);
199 // Return the ParamAttrsList that we found or created.
203 ParamAttrsList::~ParamAttrsList() {
204 ParamAttrsLists->RemoveNode(this);
207 //===----------------------------------------------------------------------===//
208 // Function Implementation
209 //===----------------------------------------------------------------------===//
211 Function::Function(const FunctionType *Ty, LinkageTypes Linkage,
212 const std::string &name, Module *ParentModule)
213 : GlobalValue(PointerType::get(Ty), Value::FunctionVal, 0, 0, Linkage, name),
215 SymTab = new ValueSymbolTable();
217 assert((getReturnType()->isFirstClassType() ||getReturnType() == Type::VoidTy)
218 && "LLVM functions cannot return aggregate values!");
220 // If the function has arguments, mark them as lazily built.
221 if (Ty->getNumParams())
222 SubclassData = 1; // Set the "has lazy arguments" bit.
224 // Make sure that we get added to a function
225 LeakDetector::addGarbageObject(this);
228 ParentModule->getFunctionList().push_back(this);
231 Function::~Function() {
232 dropAllReferences(); // After this it is safe to delete instructions.
234 // Delete all of the method arguments and unlink from symbol table...
235 ArgumentList.clear();
238 // Drop our reference to the parameter attributes, if any.
240 ParamAttrs->dropRef();
243 void Function::BuildLazyArguments() const {
244 // Create the arguments vector, all arguments start out unnamed.
245 const FunctionType *FT = getFunctionType();
246 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
247 assert(FT->getParamType(i) != Type::VoidTy &&
248 "Cannot have void typed arguments!");
249 ArgumentList.push_back(new Argument(FT->getParamType(i)));
252 // Clear the lazy arguments bit.
253 const_cast<Function*>(this)->SubclassData &= ~1;
256 size_t Function::arg_size() const {
257 return getFunctionType()->getNumParams();
259 bool Function::arg_empty() const {
260 return getFunctionType()->getNumParams() == 0;
263 void Function::setParent(Module *parent) {
265 LeakDetector::addGarbageObject(this);
268 LeakDetector::removeGarbageObject(this);
271 void Function::setParamAttrs(const ParamAttrsList *attrs) {
272 // Avoid deleting the ParamAttrsList if they are setting the
273 // attributes to the same list.
274 if (ParamAttrs == attrs)
277 // Drop reference on the old ParamAttrsList
279 ParamAttrs->dropRef();
281 // Add reference to the new ParamAttrsList
285 // Set the new ParamAttrsList.
289 const FunctionType *Function::getFunctionType() const {
290 return cast<FunctionType>(getType()->getElementType());
293 bool Function::isVarArg() const {
294 return getFunctionType()->isVarArg();
297 const Type *Function::getReturnType() const {
298 return getFunctionType()->getReturnType();
301 void Function::removeFromParent() {
302 getParent()->getFunctionList().remove(this);
305 void Function::eraseFromParent() {
306 getParent()->getFunctionList().erase(this);
309 // dropAllReferences() - This function causes all the subinstructions to "let
310 // go" of all references that they are maintaining. This allows one to
311 // 'delete' a whole class at a time, even though there may be circular
312 // references... first all references are dropped, and all use counts go to
313 // zero. Then everything is deleted for real. Note that no operations are
314 // valid on an object that has "dropped all references", except operator
317 void Function::dropAllReferences() {
318 for (iterator I = begin(), E = end(); I != E; ++I)
319 I->dropAllReferences();
320 BasicBlocks.clear(); // Delete all basic blocks...
323 /// getIntrinsicID - This method returns the ID number of the specified
324 /// function, or Intrinsic::not_intrinsic if the function is not an
325 /// intrinsic, or if the pointer is null. This value is always defined to be
326 /// zero to allow easy checking for whether a function is intrinsic or not. The
327 /// particular intrinsic functions which correspond to this value are defined in
328 /// llvm/Intrinsics.h.
330 unsigned Function::getIntrinsicID(bool noAssert) const {
331 const ValueName *ValName = this->getValueName();
334 unsigned Len = ValName->getKeyLength();
335 const char *Name = ValName->getKeyData();
337 if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
338 || Name[2] != 'v' || Name[3] != 'm')
339 return 0; // All intrinsics start with 'llvm.'
341 assert((Len != 5 || noAssert) && "'llvm.' is an invalid intrinsic name!");
343 #define GET_FUNCTION_RECOGNIZER
344 #include "llvm/Intrinsics.gen"
345 #undef GET_FUNCTION_RECOGNIZER
346 assert(noAssert && "Invalid LLVM intrinsic name");
350 std::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) {
351 assert(id < num_intrinsics && "Invalid intrinsic ID!");
352 const char * const Table[] = {
354 #define GET_INTRINSIC_NAME_TABLE
355 #include "llvm/Intrinsics.gen"
356 #undef GET_INTRINSIC_NAME_TABLE
360 std::string Result(Table[id]);
361 for (unsigned i = 0; i < numTys; ++i)
363 Result += "." + MVT::getValueTypeString(MVT::getValueType(Tys[i]));
367 const FunctionType *Intrinsic::getType(ID id, const Type **Tys,
369 const Type *ResultTy = NULL;
370 std::vector<const Type*> ArgTys;
371 bool IsVarArg = false;
373 #define GET_INTRINSIC_GENERATOR
374 #include "llvm/Intrinsics.gen"
375 #undef GET_INTRINSIC_GENERATOR
377 return FunctionType::get(ResultTy, ArgTys, IsVarArg);
380 Function *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys,
382 // There can never be multiple globals with the same name of different types,
383 // because intrinsics must be a specific type.
384 return cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys),
385 getType(id, Tys, numTys)));
388 Value *IntrinsicInst::StripPointerCasts(Value *Ptr) {
389 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
390 if (CE->getOpcode() == Instruction::BitCast) {
391 if (isa<PointerType>(CE->getOperand(0)->getType()))
392 return StripPointerCasts(CE->getOperand(0));
393 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
394 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
395 if (!CE->getOperand(i)->isNullValue())
397 return StripPointerCasts(CE->getOperand(0));
402 if (BitCastInst *CI = dyn_cast<BitCastInst>(Ptr)) {
403 if (isa<PointerType>(CI->getOperand(0)->getType()))
404 return StripPointerCasts(CI->getOperand(0));
405 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
406 if (GEP->hasAllZeroIndices())
407 return StripPointerCasts(GEP->getOperand(0));