Function.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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. #include "llvm/Module.h"
  14. #include "llvm/DerivedTypes.h"
  15. #include "llvm/IntrinsicInst.h"
  16. #include "llvm/LLVMContext.h"
  17. #include "llvm/CodeGen/ValueTypes.h"
  18. #include "llvm/Support/CallSite.h"
  19. #include "llvm/Support/LeakDetector.h"
  20. #include "llvm/Support/ManagedStatic.h"
  21. #include "llvm/Support/StringPool.h"
  22. #include "llvm/System/RWMutex.h"
  23. #include "llvm/System/Threading.h"
  24. #include "SymbolTableListTraitsImpl.h"
  25. #include "llvm/ADT/DenseMap.h"
  26. #include "llvm/ADT/StringExtras.h"
  27. using namespace llvm;
  28. // Explicit instantiations of SymbolTableListTraits since some of the methods
  29. // are not in the public header file...
  30. template class llvm::SymbolTableListTraits<Argument, Function>;
  31. template class llvm::SymbolTableListTraits<BasicBlock, Function>;
  32. //===----------------------------------------------------------------------===//
  33. // Argument Implementation
  34. //===----------------------------------------------------------------------===//
  35. Argument::Argument(const Type *Ty, const Twine &Name, Function *Par)
  36. : Value(Ty, Value::ArgumentVal) {
  37. Parent = 0;
  38. // Make sure that we get added to a function
  39. LeakDetector::addGarbageObject(this);
  40. if (Par)
  41. Par->getArgumentList().push_back(this);
  42. setName(Name);
  43. }
  44. void Argument::setParent(Function *parent) {
  45. if (getParent())
  46. LeakDetector::addGarbageObject(this);
  47. Parent = parent;
  48. if (getParent())
  49. LeakDetector::removeGarbageObject(this);
  50. }
  51. /// getArgNo - Return the index of this formal argument in its containing
  52. /// function. For example in "void foo(int a, float b)" a is 0 and b is 1.
  53. unsigned Argument::getArgNo() const {
  54. const Function *F = getParent();
  55. assert(F && "Argument is not in a function");
  56. Function::const_arg_iterator AI = F->arg_begin();
  57. unsigned ArgIdx = 0;
  58. for (; &*AI != this; ++AI)
  59. ++ArgIdx;
  60. return ArgIdx;
  61. }
  62. /// hasByValAttr - Return true if this argument has the byval attribute on it
  63. /// in its containing function.
  64. bool Argument::hasByValAttr() const {
  65. if (!getType()->isPointerTy()) return false;
  66. return getParent()->paramHasAttr(getArgNo()+1, Attribute::ByVal);
  67. }
  68. /// hasNestAttr - Return true if this argument has the nest attribute on
  69. /// it in its containing function.
  70. bool Argument::hasNestAttr() const {
  71. if (!getType()->isPointerTy()) return false;
  72. return getParent()->paramHasAttr(getArgNo()+1, Attribute::Nest);
  73. }
  74. /// hasNoAliasAttr - Return true if this argument has the noalias attribute on
  75. /// it in its containing function.
  76. bool Argument::hasNoAliasAttr() const {
  77. if (!getType()->isPointerTy()) return false;
  78. return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoAlias);
  79. }
  80. /// hasNoCaptureAttr - Return true if this argument has the nocapture attribute
  81. /// on it in its containing function.
  82. bool Argument::hasNoCaptureAttr() const {
  83. if (!getType()->isPointerTy()) return false;
  84. return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoCapture);
  85. }
  86. /// hasSRetAttr - Return true if this argument has the sret attribute on
  87. /// it in its containing function.
  88. bool Argument::hasStructRetAttr() const {
  89. if (!getType()->isPointerTy()) return false;
  90. if (this != getParent()->arg_begin())
  91. return false; // StructRet param must be first param
  92. return getParent()->paramHasAttr(1, Attribute::StructRet);
  93. }
  94. /// addAttr - Add a Attribute to an argument
  95. void Argument::addAttr(Attributes attr) {
  96. getParent()->addAttribute(getArgNo() + 1, attr);
  97. }
  98. /// removeAttr - Remove a Attribute from an argument
  99. void Argument::removeAttr(Attributes attr) {
  100. getParent()->removeAttribute(getArgNo() + 1, attr);
  101. }
  102. //===----------------------------------------------------------------------===//
  103. // Helper Methods in Function
  104. //===----------------------------------------------------------------------===//
  105. LLVMContext &Function::getContext() const {
  106. return getType()->getContext();
  107. }
  108. const FunctionType *Function::getFunctionType() const {
  109. return cast<FunctionType>(getType()->getElementType());
  110. }
  111. bool Function::isVarArg() const {
  112. return getFunctionType()->isVarArg();
  113. }
  114. const Type *Function::getReturnType() const {
  115. return getFunctionType()->getReturnType();
  116. }
  117. void Function::removeFromParent() {
  118. getParent()->getFunctionList().remove(this);
  119. }
  120. void Function::eraseFromParent() {
  121. getParent()->getFunctionList().erase(this);
  122. }
  123. //===----------------------------------------------------------------------===//
  124. // Function Implementation
  125. //===----------------------------------------------------------------------===//
  126. Function::Function(const FunctionType *Ty, LinkageTypes Linkage,
  127. const Twine &name, Module *ParentModule)
  128. : GlobalValue(PointerType::getUnqual(Ty),
  129. Value::FunctionVal, 0, 0, Linkage, name) {
  130. assert(FunctionType::isValidReturnType(getReturnType()) &&
  131. !getReturnType()->isOpaqueTy() && "invalid return type");
  132. SymTab = new ValueSymbolTable();
  133. // If the function has arguments, mark them as lazily built.
  134. if (Ty->getNumParams())
  135. setValueSubclassData(1); // Set the "has lazy arguments" bit.
  136. // Make sure that we get added to a function
  137. LeakDetector::addGarbageObject(this);
  138. if (ParentModule)
  139. ParentModule->getFunctionList().push_back(this);
  140. // Ensure intrinsics have the right parameter attributes.
  141. if (unsigned IID = getIntrinsicID())
  142. setAttributes(Intrinsic::getAttributes(Intrinsic::ID(IID)));
  143. }
  144. Function::~Function() {
  145. dropAllReferences(); // After this it is safe to delete instructions.
  146. // Delete all of the method arguments and unlink from symbol table...
  147. ArgumentList.clear();
  148. delete SymTab;
  149. // Remove the function from the on-the-side GC table.
  150. clearGC();
  151. }
  152. void Function::BuildLazyArguments() const {
  153. // Create the arguments vector, all arguments start out unnamed.
  154. const FunctionType *FT = getFunctionType();
  155. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  156. assert(!FT->getParamType(i)->isVoidTy() &&
  157. "Cannot have void typed arguments!");
  158. ArgumentList.push_back(new Argument(FT->getParamType(i)));
  159. }
  160. // Clear the lazy arguments bit.
  161. unsigned SDC = getSubclassDataFromValue();
  162. const_cast<Function*>(this)->setValueSubclassData(SDC &= ~1);
  163. }
  164. size_t Function::arg_size() const {
  165. return getFunctionType()->getNumParams();
  166. }
  167. bool Function::arg_empty() const {
  168. return getFunctionType()->getNumParams() == 0;
  169. }
  170. void Function::setParent(Module *parent) {
  171. if (getParent())
  172. LeakDetector::addGarbageObject(this);
  173. Parent = parent;
  174. if (getParent())
  175. LeakDetector::removeGarbageObject(this);
  176. }
  177. // dropAllReferences() - This function causes all the subinstructions to "let
  178. // go" of all references that they are maintaining. This allows one to
  179. // 'delete' a whole class at a time, even though there may be circular
  180. // references... first all references are dropped, and all use counts go to
  181. // zero. Then everything is deleted for real. Note that no operations are
  182. // valid on an object that has "dropped all references", except operator
  183. // delete.
  184. //
  185. void Function::dropAllReferences() {
  186. for (iterator I = begin(), E = end(); I != E; ++I)
  187. I->dropAllReferences();
  188. // Delete all basic blocks.
  189. while (!BasicBlocks.empty()) {
  190. // If there is still a reference to the block, it must be a 'blockaddress'
  191. // constant pointing to it. Just replace the BlockAddress with undef.
  192. BasicBlock *BB = BasicBlocks.begin();
  193. if (!BB->use_empty()) {
  194. BlockAddress *BA = cast<BlockAddress>(BB->use_back());
  195. BA->replaceAllUsesWith(UndefValue::get(BA->getType()));
  196. BA->destroyConstant();
  197. }
  198. BB->eraseFromParent();
  199. }
  200. }
  201. void Function::addAttribute(unsigned i, Attributes attr) {
  202. AttrListPtr PAL = getAttributes();
  203. PAL = PAL.addAttr(i, attr);
  204. setAttributes(PAL);
  205. }
  206. void Function::removeAttribute(unsigned i, Attributes attr) {
  207. AttrListPtr PAL = getAttributes();
  208. PAL = PAL.removeAttr(i, attr);
  209. setAttributes(PAL);
  210. }
  211. // Maintain the GC name for each function in an on-the-side table. This saves
  212. // allocating an additional word in Function for programs which do not use GC
  213. // (i.e., most programs) at the cost of increased overhead for clients which do
  214. // use GC.
  215. static DenseMap<const Function*,PooledStringPtr> *GCNames;
  216. static StringPool *GCNamePool;
  217. static ManagedStatic<sys::SmartRWMutex<true> > GCLock;
  218. bool Function::hasGC() const {
  219. sys::SmartScopedReader<true> Reader(*GCLock);
  220. return GCNames && GCNames->count(this);
  221. }
  222. const char *Function::getGC() const {
  223. assert(hasGC() && "Function has no collector");
  224. sys::SmartScopedReader<true> Reader(*GCLock);
  225. return *(*GCNames)[this];
  226. }
  227. void Function::setGC(const char *Str) {
  228. sys::SmartScopedWriter<true> Writer(*GCLock);
  229. if (!GCNamePool)
  230. GCNamePool = new StringPool();
  231. if (!GCNames)
  232. GCNames = new DenseMap<const Function*,PooledStringPtr>();
  233. (*GCNames)[this] = GCNamePool->intern(Str);
  234. }
  235. void Function::clearGC() {
  236. sys::SmartScopedWriter<true> Writer(*GCLock);
  237. if (GCNames) {
  238. GCNames->erase(this);
  239. if (GCNames->empty()) {
  240. delete GCNames;
  241. GCNames = 0;
  242. if (GCNamePool->empty()) {
  243. delete GCNamePool;
  244. GCNamePool = 0;
  245. }
  246. }
  247. }
  248. }
  249. /// copyAttributesFrom - copy all additional attributes (those not needed to
  250. /// create a Function) from the Function Src to this one.
  251. void Function::copyAttributesFrom(const GlobalValue *Src) {
  252. assert(isa<Function>(Src) && "Expected a Function!");
  253. GlobalValue::copyAttributesFrom(Src);
  254. const Function *SrcF = cast<Function>(Src);
  255. setCallingConv(SrcF->getCallingConv());
  256. setAttributes(SrcF->getAttributes());
  257. if (SrcF->hasGC())
  258. setGC(SrcF->getGC());
  259. else
  260. clearGC();
  261. }
  262. /// getIntrinsicID - This method returns the ID number of the specified
  263. /// function, or Intrinsic::not_intrinsic if the function is not an
  264. /// intrinsic, or if the pointer is null. This value is always defined to be
  265. /// zero to allow easy checking for whether a function is intrinsic or not. The
  266. /// particular intrinsic functions which correspond to this value are defined in
  267. /// llvm/Intrinsics.h.
  268. ///
  269. unsigned Function::getIntrinsicID() const {
  270. const ValueName *ValName = this->getValueName();
  271. if (!ValName)
  272. return 0;
  273. unsigned Len = ValName->getKeyLength();
  274. const char *Name = ValName->getKeyData();
  275. if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
  276. || Name[2] != 'v' || Name[3] != 'm')
  277. return 0; // All intrinsics start with 'llvm.'
  278. #define GET_FUNCTION_RECOGNIZER
  279. #include "llvm/Intrinsics.gen"
  280. #undef GET_FUNCTION_RECOGNIZER
  281. return 0;
  282. }
  283. std::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) {
  284. assert(id < num_intrinsics && "Invalid intrinsic ID!");
  285. const char * const Table[] = {
  286. "not_intrinsic",
  287. #define GET_INTRINSIC_NAME_TABLE
  288. #include "llvm/Intrinsics.gen"
  289. #undef GET_INTRINSIC_NAME_TABLE
  290. };
  291. if (numTys == 0)
  292. return Table[id];
  293. std::string Result(Table[id]);
  294. for (unsigned i = 0; i < numTys; ++i) {
  295. if (const PointerType* PTyp = dyn_cast<PointerType>(Tys[i])) {
  296. Result += ".p" + llvm::utostr(PTyp->getAddressSpace()) +
  297. EVT::getEVT(PTyp->getElementType()).getEVTString();
  298. }
  299. else if (Tys[i])
  300. Result += "." + EVT::getEVT(Tys[i]).getEVTString();
  301. }
  302. return Result;
  303. }
  304. const FunctionType *Intrinsic::getType(LLVMContext &Context,
  305. ID id, const Type **Tys,
  306. unsigned numTys) {
  307. const Type *ResultTy = NULL;
  308. std::vector<const Type*> ArgTys;
  309. bool IsVarArg = false;
  310. #define GET_INTRINSIC_GENERATOR
  311. #include "llvm/Intrinsics.gen"
  312. #undef GET_INTRINSIC_GENERATOR
  313. return FunctionType::get(ResultTy, ArgTys, IsVarArg);
  314. }
  315. bool Intrinsic::isOverloaded(ID id) {
  316. const bool OTable[] = {
  317. false,
  318. #define GET_INTRINSIC_OVERLOAD_TABLE
  319. #include "llvm/Intrinsics.gen"
  320. #undef GET_INTRINSIC_OVERLOAD_TABLE
  321. };
  322. return OTable[id];
  323. }
  324. /// This defines the "Intrinsic::getAttributes(ID id)" method.
  325. #define GET_INTRINSIC_ATTRIBUTES
  326. #include "llvm/Intrinsics.gen"
  327. #undef GET_INTRINSIC_ATTRIBUTES
  328. Function *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys,
  329. unsigned numTys) {
  330. // There can never be multiple globals with the same name of different types,
  331. // because intrinsics must be a specific type.
  332. return
  333. cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys),
  334. getType(M->getContext(),
  335. id, Tys, numTys)));
  336. }
  337. // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
  338. #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
  339. #include "llvm/Intrinsics.gen"
  340. #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
  341. /// hasAddressTaken - returns true if there are any uses of this function
  342. /// other than direct calls or invokes to it.
  343. bool Function::hasAddressTaken(const User* *PutOffender) const {
  344. for (Value::use_const_iterator I = use_begin(), E = use_end(); I != E; ++I) {
  345. const User *U = *I;
  346. if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
  347. return PutOffender ? (*PutOffender = U, true) : true;
  348. CallSite CS(const_cast<Instruction*>(static_cast<const Instruction*>(U)));
  349. if (!CS.isCallee(I))
  350. return PutOffender ? (*PutOffender = U, true) : true;
  351. }
  352. return false;
  353. }
  354. // vim: sw=2 ai