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/ManagedStatic.h"
20 #include "llvm/Support/StringPool.h"
21 #include "SymbolTableListTraitsImpl.h"
22 #include "llvm/ADT/BitVector.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/StringExtras.h"
27 BasicBlock *ilist_traits<BasicBlock>::createSentinel() {
28 BasicBlock *Ret = new BasicBlock();
29 // This should not be garbage monitored.
30 LeakDetector::removeGarbageObject(Ret);
34 iplist<BasicBlock> &ilist_traits<BasicBlock>::getList(Function *F) {
35 return F->getBasicBlockList();
38 Argument *ilist_traits<Argument>::createSentinel() {
39 Argument *Ret = new Argument(Type::Int32Ty);
40 // This should not be garbage monitored.
41 LeakDetector::removeGarbageObject(Ret);
45 iplist<Argument> &ilist_traits<Argument>::getList(Function *F) {
46 return F->getArgumentList();
49 // Explicit instantiations of SymbolTableListTraits since some of the methods
50 // are not in the public header file...
51 template class SymbolTableListTraits<Argument, Function>;
52 template class SymbolTableListTraits<BasicBlock, Function>;
54 //===----------------------------------------------------------------------===//
55 // Argument Implementation
56 //===----------------------------------------------------------------------===//
58 Argument::Argument(const Type *Ty, const std::string &Name, Function *Par)
59 : Value(Ty, Value::ArgumentVal) {
62 // Make sure that we get added to a function
63 LeakDetector::addGarbageObject(this);
66 Par->getArgumentList().push_back(this);
70 void Argument::setParent(Function *parent) {
72 LeakDetector::addGarbageObject(this);
75 LeakDetector::removeGarbageObject(this);
78 //===----------------------------------------------------------------------===//
79 // ParamAttrsList Implementation
80 //===----------------------------------------------------------------------===//
83 ParamAttrsList::getParamAttrs(uint16_t Index) const {
84 unsigned limit = attrs.size();
85 for (unsigned i = 0; i < limit && attrs[i].index <= Index; ++i)
86 if (attrs[i].index == Index)
87 return attrs[i].attrs;
88 return ParamAttr::None;
92 ParamAttrsList::getParamAttrsText(uint16_t Attrs) {
94 if (Attrs & ParamAttr::ZExt)
96 if (Attrs & ParamAttr::SExt)
98 if (Attrs & ParamAttr::NoReturn)
99 Result += "noreturn ";
100 if (Attrs & ParamAttr::NoUnwind)
101 Result += "nounwind ";
102 if (Attrs & ParamAttr::InReg)
104 if (Attrs & ParamAttr::NoAlias)
105 Result += "noalias ";
106 if (Attrs & ParamAttr::StructRet)
108 if (Attrs & ParamAttr::ByVal)
110 if (Attrs & ParamAttr::Nest)
112 if (Attrs & ParamAttr::ReadNone)
113 Result += "readnone ";
114 if (Attrs & ParamAttr::ReadOnly)
115 Result += "readonly ";
119 /// onlyInformative - Returns whether only informative attributes are set.
120 static inline bool onlyInformative(uint16_t attrs) {
121 return !(attrs & ~ParamAttr::Informative);
125 ParamAttrsList::areCompatible(const ParamAttrsList *A, const ParamAttrsList *B){
128 unsigned ASize = A ? A->size() : 0;
129 unsigned BSize = B ? B->size() : 0;
133 while (AIndex < ASize && BIndex < BSize) {
134 uint16_t AIdx = A->getParamIndex(AIndex);
135 uint16_t BIdx = B->getParamIndex(BIndex);
136 uint16_t AAttrs = A->getParamAttrsAtIndex(AIndex);
137 uint16_t BAttrs = B->getParamAttrsAtIndex(AIndex);
140 if (!onlyInformative(AAttrs))
143 } else if (BIdx < AIdx) {
144 if (!onlyInformative(BAttrs))
148 if (!onlyInformative(AAttrs ^ BAttrs))
154 for (; AIndex < ASize; ++AIndex)
155 if (!onlyInformative(A->getParamAttrsAtIndex(AIndex)))
157 for (; BIndex < BSize; ++BIndex)
158 if (!onlyInformative(B->getParamAttrsAtIndex(AIndex)))
163 void ParamAttrsList::Profile(FoldingSetNodeID &ID) const {
164 for (unsigned i = 0; i < attrs.size(); ++i)
165 ID.AddInteger(unsigned(attrs[i].attrs) << 16 | unsigned(attrs[i].index));
168 static ManagedStatic<FoldingSet<ParamAttrsList> > ParamAttrsLists;
170 const ParamAttrsList *
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 const ParamAttrsList *
204 ParamAttrsList::getModified(const ParamAttrsList *PAL,
205 const ParamAttrsVector &modVec) {
210 for (unsigned i = 0, e = modVec.size(); i < e; ++i)
211 assert((!i || modVec[i-1].index < modVec[i].index)
212 && "Misordered ParamAttrsList!");
216 // Strip any instances of ParamAttr::None from modVec before calling 'get'.
217 ParamAttrsVector newVec;
218 for (unsigned i = 0, e = modVec.size(); i < e; ++i)
219 if (modVec[i].attrs != ParamAttr::None)
220 newVec.push_back(modVec[i]);
224 const ParamAttrsVector &oldVec = PAL->attrs;
226 ParamAttrsVector newVec;
229 unsigned oldE = oldVec.size();
230 unsigned modE = modVec.size();
232 while (oldI < oldE && modI < modE) {
233 uint16_t oldIndex = oldVec[oldI].index;
234 uint16_t modIndex = modVec[modI].index;
236 if (oldIndex < modIndex) {
237 newVec.push_back(oldVec[oldI]);
239 } else if (modIndex < oldIndex) {
240 if (modVec[modI].attrs != ParamAttr::None)
241 newVec.push_back(modVec[modI]);
244 // Same index - overwrite or delete existing attributes.
245 if (modVec[modI].attrs != ParamAttr::None)
246 newVec.push_back(modVec[modI]);
252 for (; oldI < oldE; ++oldI)
253 newVec.push_back(oldVec[oldI]);
254 for (; modI < modE; ++modI)
255 if (modVec[modI].attrs != ParamAttr::None)
256 newVec.push_back(modVec[modI]);
261 const ParamAttrsList *
262 ParamAttrsList::includeAttrs(const ParamAttrsList *PAL,
263 uint16_t idx, uint16_t attrs) {
264 uint16_t OldAttrs = PAL ? PAL->getParamAttrs(idx) : 0;
265 uint16_t NewAttrs = OldAttrs | attrs;
266 if (NewAttrs == OldAttrs)
269 ParamAttrsVector modVec;
270 modVec.push_back(ParamAttrsWithIndex::get(idx, NewAttrs));
271 return getModified(PAL, modVec);
274 const ParamAttrsList *
275 ParamAttrsList::excludeAttrs(const ParamAttrsList *PAL,
276 uint16_t idx, uint16_t attrs) {
277 uint16_t OldAttrs = PAL ? PAL->getParamAttrs(idx) : 0;
278 uint16_t NewAttrs = OldAttrs & ~attrs;
279 if (NewAttrs == OldAttrs)
282 ParamAttrsVector modVec;
283 modVec.push_back(ParamAttrsWithIndex::get(idx, NewAttrs));
284 return getModified(PAL, modVec);
287 ParamAttrsList::~ParamAttrsList() {
288 ParamAttrsLists->RemoveNode(this);
291 //===----------------------------------------------------------------------===//
292 // Function Implementation
293 //===----------------------------------------------------------------------===//
295 Function::Function(const FunctionType *Ty, LinkageTypes Linkage,
296 const std::string &name, Module *ParentModule)
297 : GlobalValue(PointerType::getUnqual(Ty),
298 Value::FunctionVal, 0, 0, Linkage, name),
300 SymTab = new ValueSymbolTable();
302 assert((getReturnType()->isFirstClassType() ||getReturnType() == Type::VoidTy)
303 && "LLVM functions cannot return aggregate values!");
305 // If the function has arguments, mark them as lazily built.
306 if (Ty->getNumParams())
307 SubclassData = 1; // Set the "has lazy arguments" bit.
309 // Make sure that we get added to a function
310 LeakDetector::addGarbageObject(this);
313 ParentModule->getFunctionList().push_back(this);
316 Function::~Function() {
317 dropAllReferences(); // After this it is safe to delete instructions.
319 // Delete all of the method arguments and unlink from symbol table...
320 ArgumentList.clear();
323 // Drop our reference to the parameter attributes, if any.
325 ParamAttrs->dropRef();
327 // Remove the function from the on-the-side collector table.
331 void Function::BuildLazyArguments() const {
332 // Create the arguments vector, all arguments start out unnamed.
333 const FunctionType *FT = getFunctionType();
334 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
335 assert(FT->getParamType(i) != Type::VoidTy &&
336 "Cannot have void typed arguments!");
337 ArgumentList.push_back(new Argument(FT->getParamType(i)));
340 // Clear the lazy arguments bit.
341 const_cast<Function*>(this)->SubclassData &= ~1;
344 size_t Function::arg_size() const {
345 return getFunctionType()->getNumParams();
347 bool Function::arg_empty() const {
348 return getFunctionType()->getNumParams() == 0;
351 void Function::setParent(Module *parent) {
353 LeakDetector::addGarbageObject(this);
356 LeakDetector::removeGarbageObject(this);
359 void Function::setParamAttrs(const ParamAttrsList *attrs) {
360 // Avoid deleting the ParamAttrsList if they are setting the
361 // attributes to the same list.
362 if (ParamAttrs == attrs)
365 // Drop reference on the old ParamAttrsList
367 ParamAttrs->dropRef();
369 // Add reference to the new ParamAttrsList
373 // Set the new ParamAttrsList.
377 const FunctionType *Function::getFunctionType() const {
378 return cast<FunctionType>(getType()->getElementType());
381 bool Function::isVarArg() const {
382 return getFunctionType()->isVarArg();
385 const Type *Function::getReturnType() const {
386 return getFunctionType()->getReturnType();
389 void Function::removeFromParent() {
390 getParent()->getFunctionList().remove(this);
393 void Function::eraseFromParent() {
394 getParent()->getFunctionList().erase(this);
397 // dropAllReferences() - This function causes all the subinstructions to "let
398 // go" of all references that they are maintaining. This allows one to
399 // 'delete' a whole class at a time, even though there may be circular
400 // references... first all references are dropped, and all use counts go to
401 // zero. Then everything is deleted for real. Note that no operations are
402 // valid on an object that has "dropped all references", except operator
405 void Function::dropAllReferences() {
406 for (iterator I = begin(), E = end(); I != E; ++I)
407 I->dropAllReferences();
408 BasicBlocks.clear(); // Delete all basic blocks...
411 // Maintain the collector name for each function in an on-the-side table. This
412 // saves allocating an additional word in Function for programs which do not use
413 // GC (i.e., most programs) at the cost of increased overhead for clients which
415 static DenseMap<const Function*,PooledStringPtr> *CollectorNames;
416 static StringPool *CollectorNamePool;
418 bool Function::hasCollector() const {
419 return CollectorNames && CollectorNames->count(this);
422 const char *Function::getCollector() const {
423 assert(hasCollector() && "Function has no collector");
424 return *(*CollectorNames)[this];
427 void Function::setCollector(const char *Str) {
428 if (!CollectorNamePool)
429 CollectorNamePool = new StringPool();
431 CollectorNames = new DenseMap<const Function*,PooledStringPtr>();
432 (*CollectorNames)[this] = CollectorNamePool->intern(Str);
435 void Function::clearCollector() {
436 if (CollectorNames) {
437 CollectorNames->erase(this);
438 if (CollectorNames->empty()) {
439 delete CollectorNames;
441 if (CollectorNamePool->empty()) {
442 delete CollectorNamePool;
443 CollectorNamePool = 0;
449 /// getIntrinsicID - This method returns the ID number of the specified
450 /// function, or Intrinsic::not_intrinsic if the function is not an
451 /// intrinsic, or if the pointer is null. This value is always defined to be
452 /// zero to allow easy checking for whether a function is intrinsic or not. The
453 /// particular intrinsic functions which correspond to this value are defined in
454 /// llvm/Intrinsics.h.
456 unsigned Function::getIntrinsicID(bool noAssert) const {
457 const ValueName *ValName = this->getValueName();
460 unsigned Len = ValName->getKeyLength();
461 const char *Name = ValName->getKeyData();
463 if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
464 || Name[2] != 'v' || Name[3] != 'm')
465 return 0; // All intrinsics start with 'llvm.'
467 assert((Len != 5 || noAssert) && "'llvm.' is an invalid intrinsic name!");
469 #define GET_FUNCTION_RECOGNIZER
470 #include "llvm/Intrinsics.gen"
471 #undef GET_FUNCTION_RECOGNIZER
472 assert(noAssert && "Invalid LLVM intrinsic name");
476 std::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) {
477 assert(id < num_intrinsics && "Invalid intrinsic ID!");
478 const char * const Table[] = {
480 #define GET_INTRINSIC_NAME_TABLE
481 #include "llvm/Intrinsics.gen"
482 #undef GET_INTRINSIC_NAME_TABLE
486 std::string Result(Table[id]);
487 for (unsigned i = 0; i < numTys; ++i)
489 Result += "." + MVT::getValueTypeString(MVT::getValueType(Tys[i]));
493 const FunctionType *Intrinsic::getType(ID id, const Type **Tys,
495 const Type *ResultTy = NULL;
496 std::vector<const Type*> ArgTys;
497 bool IsVarArg = false;
499 #define GET_INTRINSIC_GENERATOR
500 #include "llvm/Intrinsics.gen"
501 #undef GET_INTRINSIC_GENERATOR
503 return FunctionType::get(ResultTy, ArgTys, IsVarArg);
506 const ParamAttrsList *Intrinsic::getParamAttrs(ID id) {
507 static const ParamAttrsList *IntrinsicAttributes[Intrinsic::num_intrinsics];
509 if (IntrinsicAttributes[id])
510 return IntrinsicAttributes[id];
512 ParamAttrsVector Attrs;
513 uint16_t Attr = ParamAttr::None;
515 #define GET_INTRINSIC_ATTRIBUTES
516 #include "llvm/Intrinsics.gen"
517 #undef GET_INTRINSIC_ATTRIBUTES
519 // Intrinsics cannot throw exceptions.
520 Attr |= ParamAttr::NoUnwind;
522 Attrs.push_back(ParamAttrsWithIndex::get(0, Attr));
523 IntrinsicAttributes[id] = ParamAttrsList::get(Attrs);
524 return IntrinsicAttributes[id];
527 Function *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys,
529 // There can never be multiple globals with the same name of different types,
530 // because intrinsics must be a specific type.
532 cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys),
533 getType(id, Tys, numTys)));
534 F->setParamAttrs(getParamAttrs(id));
538 Value *IntrinsicInst::StripPointerCasts(Value *Ptr) {
539 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
540 if (CE->getOpcode() == Instruction::BitCast) {
541 if (isa<PointerType>(CE->getOperand(0)->getType()))
542 return StripPointerCasts(CE->getOperand(0));
543 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
544 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
545 if (!CE->getOperand(i)->isNullValue())
547 return StripPointerCasts(CE->getOperand(0));
552 if (BitCastInst *CI = dyn_cast<BitCastInst>(Ptr)) {
553 if (isa<PointerType>(CI->getOperand(0)->getType()))
554 return StripPointerCasts(CI->getOperand(0));
555 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
556 if (GEP->hasAllZeroIndices())
557 return StripPointerCasts(GEP->getOperand(0));