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. 11 // 12 //===----------------------------------------------------------------------===// 13 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; 30 31 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>; 36 37 //===----------------------------------------------------------------------===// 38 // Argument Implementation 39 //===----------------------------------------------------------------------===// 40 41 Argument::Argument(Type *Ty, const Twine &Name, Function *Par) 42 : Value(Ty, Value::ArgumentVal) { 43 Parent = 0; 44 45 // Make sure that we get added to a function 46 LeakDetector::addGarbageObject(this); 47 48 if (Par) 49 Par->getArgumentList().push_back(this); 50 setName(Name); 51 } 52 53 void Argument::setParent(Function *parent) { 54 if (getParent()) 55 LeakDetector::addGarbageObject(this); 56 Parent = parent; 57 if (getParent()) 58 LeakDetector::removeGarbageObject(this); 59 } 60 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"); 66 67 Function::const_arg_iterator AI = F->arg_begin(); 68 unsigned ArgIdx = 0; 69 for (; &*AI != this; ++AI) 70 ++ArgIdx; 71 72 return ArgIdx; 73 } 74 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); 80 } 81 82 unsigned Argument::getParamAlignment() const { 83 assert(getType()->isPointerTy() && "Only pointers have alignments"); 84 return getParent()->getParamAlignment(getArgNo()+1); 85 86 } 87 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); 93 } 94 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); 100 } 101 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); 107 } 108 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); 116 } 117 118 /// addAttr - Add a Attribute to an argument 119 void Argument::addAttr(Attributes attr) { 120 getParent()->addAttribute(getArgNo() + 1, attr); 121 } 122 123 /// removeAttr - Remove a Attribute from an argument 124 void Argument::removeAttr(Attributes attr) { 125 getParent()->removeAttribute(getArgNo() + 1, attr); 126 } 127 128 129 //===----------------------------------------------------------------------===// 130 // Helper Methods in Function 131 //===----------------------------------------------------------------------===// 132 133 LLVMContext &Function::getContext() const { 134 return getType()->getContext(); 135 } 136 137 FunctionType *Function::getFunctionType() const { 138 return cast<FunctionType>(getType()->getElementType()); 139 } 140 141 bool Function::isVarArg() const { 142 return getFunctionType()->isVarArg(); 143 } 144 145 Type *Function::getReturnType() const { 146 return getFunctionType()->getReturnType(); 147 } 148 149 void Function::removeFromParent() { 150 getParent()->getFunctionList().remove(this); 151 } 152 153 void Function::eraseFromParent() { 154 getParent()->getFunctionList().erase(this); 155 } 156 157 //===----------------------------------------------------------------------===// 158 // Function Implementation 159 //===----------------------------------------------------------------------===// 160 161 Function::Function(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(); 168 169 // If the function has arguments, mark them as lazily built. 170 if (Ty->getNumParams()) 171 setValueSubclassData(1); // Set the "has lazy arguments" bit. 172 173 // Make sure that we get added to a function 174 LeakDetector::addGarbageObject(this); 175 176 if (ParentModule) 177 ParentModule->getFunctionList().push_back(this); 178 179 // Ensure intrinsics have the right parameter attributes. 180 if (unsigned IID = getIntrinsicID()) 181 setAttributes(Intrinsic::getAttributes(Intrinsic::ID(IID))); 182 183 } 184 185 Function::~Function() { 186 dropAllReferences(); // After this it is safe to delete instructions. 187 188 // Delete all of the method arguments and unlink from symbol table... 189 ArgumentList.clear(); 190 delete SymTab; 191 192 // Remove the function from the on-the-side GC table. 193 clearGC(); 194 } 195 196 void Function::BuildLazyArguments() const { 197 // Create the arguments vector, all arguments start out unnamed. 198 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))); 203 } 204 205 // Clear the lazy arguments bit. 206 unsigned SDC = getSubclassDataFromValue(); 207 const_cast<Function*>(this)->setValueSubclassData(SDC &= ~1); 208 } 209 210 size_t Function::arg_size() const { 211 return getFunctionType()->getNumParams(); 212 } 213 bool Function::arg_empty() const { 214 return getFunctionType()->getNumParams() == 0; 215 } 216 217 void Function::setParent(Module *parent) { 218 if (getParent()) 219 LeakDetector::addGarbageObject(this); 220 Parent = parent; 221 if (getParent()) 222 LeakDetector::removeGarbageObject(this); 223 } 224 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. 232 // 233 void Function::dropAllReferences() { 234 for (iterator I = begin(), E = end(); I != E; ++I) 235 I->dropAllReferences(); 236 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(); 241 } 242 243 void Function::addAttribute(unsigned i, Attributes attr) { 244 AttrListPtr PAL = getAttributes(); 245 PAL = PAL.addAttr(i, attr); 246 setAttributes(PAL); 247 } 248 249 void Function::removeAttribute(unsigned i, Attributes attr) { 250 AttrListPtr PAL = getAttributes(); 251 PAL = PAL.removeAttr(i, attr); 252 setAttributes(PAL); 253 } 254 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; 262 263 bool Function::hasGC() const { 264 sys::SmartScopedReader<true> Reader(*GCLock); 265 return GCNames && GCNames->count(this); 266 } 267 268 const char *Function::getGC() const { 269 assert(hasGC() && "Function has no collector"); 270 sys::SmartScopedReader<true> Reader(*GCLock); 271 return *(*GCNames)[this]; 272 } 273 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); 281 } 282 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; 293 } 294 } 295 } 296 } 297 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(); 310 } 311 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. 318 /// 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(); 325 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.' 329 330 #define GET_FUNCTION_RECOGNIZER 331 #include "llvm/Intrinsics.gen" 332 #undef GET_FUNCTION_RECOGNIZER 333 return 0; 334 } 335 336 std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) { 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 343 }; 344 if (Tys.empty()) 345 return Table[id]; 346 std::string Result(Table[id]); 347 for (unsigned i = 0; i < Tys.size(); ++i) { 348 if (PointerType* PTyp = dyn_cast<PointerType>(Tys[i])) { 349 Result += ".p" + llvm::utostr(PTyp->getAddressSpace()) + 350 EVT::getEVT(PTyp->getElementType()).getEVTString(); 351 } 352 else if (Tys[i]) 353 Result += "." + EVT::getEVT(Tys[i]).getEVTString(); 354 } 355 return Result; 356 } 357 358 FunctionType *Intrinsic::getType(LLVMContext &Context, 359 ID id, ArrayRef<Type*> Tys) { 360 Type *ResultTy = NULL; 361 std::vector<Type*> ArgTys; 362 bool IsVarArg = false; 363 364 #define GET_INTRINSIC_GENERATOR 365 #include "llvm/Intrinsics.gen" 366 #undef GET_INTRINSIC_GENERATOR 367 368 return FunctionType::get(ResultTy, ArgTys, IsVarArg); 369 } 370 371 bool Intrinsic::isOverloaded(ID id) { 372 static const bool OTable[] = { 373 false, 374 #define GET_INTRINSIC_OVERLOAD_TABLE 375 #include "llvm/Intrinsics.gen" 376 #undef GET_INTRINSIC_OVERLOAD_TABLE 377 }; 378 return OTable[id]; 379 } 380 381 /// This defines the "Intrinsic::getAttributes(ID id)" method. 382 #define GET_INTRINSIC_ATTRIBUTES 383 #include "llvm/Intrinsics.gen" 384 #undef GET_INTRINSIC_ATTRIBUTES 385 386 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) { 387 // There can never be multiple globals with the same name of different types, 388 // because intrinsics must be a specific type. 389 return 390 cast<Function>(M->getOrInsertFunction(getName(id, Tys), 391 getType(M->getContext(), id, Tys))); 392 } 393 394 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method. 395 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN 396 #include "llvm/Intrinsics.gen" 397 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN 398 399 /// hasAddressTaken - returns true if there are any uses of this function 400 /// other than direct calls or invokes to it. 401 bool Function::hasAddressTaken(const User* *PutOffender) const { 402 for (Value::const_use_iterator I = use_begin(), E = use_end(); I != E; ++I) { 403 const User *U = *I; 404 if (!isa<CallInst>(U) && !isa<InvokeInst>(U)) 405 return PutOffender ? (*PutOffender = U, true) : true; 406 ImmutableCallSite CS(cast<Instruction>(U)); 407 if (!CS.isCallee(I)) 408 return PutOffender ? (*PutOffender = U, true) : true; 409 } 410 return false; 411 } 412 413 /// callsFunctionThatReturnsTwice - Return true if the function has a call to 414 /// setjmp or other function that gcc recognizes as "returning twice". 415 /// 416 /// FIXME: Remove after <rdar://problem/8031714> is fixed. 417 /// FIXME: Is the above FIXME valid? 418 bool Function::callsFunctionThatReturnsTwice() const { 419 const Module *M = this->getParent(); 420 static const char *ReturnsTwiceFns[] = { 421 "_setjmp", 422 "setjmp", 423 "sigsetjmp", 424 "setjmp_syscall", 425 "savectx", 426 "qsetjmp", 427 "vfork", 428 "getcontext" 429 }; 430 431 for (unsigned I = 0; I < array_lengthof(ReturnsTwiceFns); ++I) 432 if (const Function *Callee = M->getFunction(ReturnsTwiceFns[I])) { 433 if (!Callee->use_empty()) 434 for (Value::const_use_iterator 435 I = Callee->use_begin(), E = Callee->use_end(); 436 I != E; ++I) 437 if (const CallInst *CI = dyn_cast<CallInst>(*I)) 438 if (CI->getParent()->getParent() == this) 439 return true; 440 } 441 442 return false; 443 } 444 445 // vim: sw=2 ai 446