FunctionAttrs.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. //===- FunctionAttrs.cpp - Pass which marks functions readnone or readonly ===//
  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 a simple interprocedural pass which walks the
  11. // call-graph, looking for functions which do not access or only read
  12. // non-local memory, and marking them readnone/readonly. In addition,
  13. // it marks function arguments (of pointer type) 'nocapture' if a call
  14. // to the function does not create any copies of the pointer value that
  15. // outlive the call. This more or less means that the pointer is only
  16. // dereferenced, and not returned from the function or stored in a global.
  17. // This pass is implemented as a bottom-up traversal of the call-graph.
  18. //
  19. //===----------------------------------------------------------------------===//
  20. #define DEBUG_TYPE "functionattrs"
  21. #include "llvm/Transforms/IPO.h"
  22. #include "llvm/CallGraphSCCPass.h"
  23. #include "llvm/GlobalVariable.h"
  24. #include "llvm/IntrinsicInst.h"
  25. #include "llvm/Analysis/AliasAnalysis.h"
  26. #include "llvm/Analysis/CallGraph.h"
  27. #include "llvm/Analysis/CaptureTracking.h"
  28. #include "llvm/Analysis/MallocHelper.h"
  29. #include "llvm/ADT/SmallSet.h"
  30. #include "llvm/ADT/Statistic.h"
  31. #include "llvm/ADT/UniqueVector.h"
  32. #include "llvm/Support/InstIterator.h"
  33. using namespace llvm;
  34. STATISTIC(NumReadNone, "Number of functions marked readnone");
  35. STATISTIC(NumReadOnly, "Number of functions marked readonly");
  36. STATISTIC(NumNoCapture, "Number of arguments marked nocapture");
  37. STATISTIC(NumNoAlias, "Number of function returns marked noalias");
  38. namespace {
  39. struct FunctionAttrs : public CallGraphSCCPass {
  40. static char ID; // Pass identification, replacement for typeid
  41. FunctionAttrs() : CallGraphSCCPass(&ID) {}
  42. // runOnSCC - Analyze the SCC, performing the transformation if possible.
  43. bool runOnSCC(std::vector<CallGraphNode *> &SCC);
  44. // AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
  45. bool AddReadAttrs(const std::vector<CallGraphNode *> &SCC);
  46. // AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
  47. bool AddNoCaptureAttrs(const std::vector<CallGraphNode *> &SCC);
  48. // IsFunctionMallocLike - Does this function allocate new memory?
  49. bool IsFunctionMallocLike(Function *F,
  50. SmallPtrSet<Function*, 8> &) const;
  51. // AddNoAliasAttrs - Deduce noalias attributes for the SCC.
  52. bool AddNoAliasAttrs(const std::vector<CallGraphNode *> &SCC);
  53. virtual void getAnalysisUsage(AnalysisUsage &AU) const {
  54. AU.setPreservesCFG();
  55. CallGraphSCCPass::getAnalysisUsage(AU);
  56. }
  57. bool PointsToLocalMemory(Value *V);
  58. };
  59. }
  60. char FunctionAttrs::ID = 0;
  61. static RegisterPass<FunctionAttrs>
  62. X("functionattrs", "Deduce function attributes");
  63. Pass *llvm::createFunctionAttrsPass() { return new FunctionAttrs(); }
  64. /// PointsToLocalMemory - Returns whether the given pointer value points to
  65. /// memory that is local to the function. Global constants are considered
  66. /// local to all functions.
  67. bool FunctionAttrs::PointsToLocalMemory(Value *V) {
  68. V = V->getUnderlyingObject();
  69. // An alloca instruction defines local memory.
  70. if (isa<AllocaInst>(V))
  71. return true;
  72. // A global constant counts as local memory for our purposes.
  73. if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
  74. return GV->isConstant();
  75. // Could look through phi nodes and selects here, but it doesn't seem
  76. // to be useful in practice.
  77. return false;
  78. }
  79. /// AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
  80. bool FunctionAttrs::AddReadAttrs(const std::vector<CallGraphNode *> &SCC) {
  81. SmallPtrSet<Function*, 8> SCCNodes;
  82. // Fill SCCNodes with the elements of the SCC. Used for quickly
  83. // looking up whether a given CallGraphNode is in this SCC.
  84. for (unsigned i = 0, e = SCC.size(); i != e; ++i)
  85. SCCNodes.insert(SCC[i]->getFunction());
  86. // Check if any of the functions in the SCC read or write memory. If they
  87. // write memory then they can't be marked readnone or readonly.
  88. bool ReadsMemory = false;
  89. for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
  90. Function *F = SCC[i]->getFunction();
  91. if (F == 0)
  92. // External node - may write memory. Just give up.
  93. return false;
  94. if (F->doesNotAccessMemory())
  95. // Already perfect!
  96. continue;
  97. // Definitions with weak linkage may be overridden at linktime with
  98. // something that writes memory, so treat them like declarations.
  99. if (F->isDeclaration() || F->mayBeOverridden()) {
  100. if (!F->onlyReadsMemory())
  101. // May write memory. Just give up.
  102. return false;
  103. ReadsMemory = true;
  104. continue;
  105. }
  106. // Scan the function body for instructions that may read or write memory.
  107. for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
  108. Instruction *I = &*II;
  109. // Some instructions can be ignored even if they read or write memory.
  110. // Detect these now, skipping to the next instruction if one is found.
  111. CallSite CS = CallSite::get(I);
  112. if (CS.getInstruction() && CS.getCalledFunction()) {
  113. // Ignore calls to functions in the same SCC.
  114. if (SCCNodes.count(CS.getCalledFunction()))
  115. continue;
  116. } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
  117. // Ignore loads from local memory.
  118. if (PointsToLocalMemory(LI->getPointerOperand()))
  119. continue;
  120. } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
  121. // Ignore stores to local memory.
  122. if (PointsToLocalMemory(SI->getPointerOperand()))
  123. continue;
  124. }
  125. // Any remaining instructions need to be taken seriously! Check if they
  126. // read or write memory.
  127. if (I->mayWriteToMemory())
  128. // Writes memory. Just give up.
  129. return false;
  130. if (isMalloc(I))
  131. // malloc claims not to write memory! PR3754.
  132. return false;
  133. // If this instruction may read memory, remember that.
  134. ReadsMemory |= I->mayReadFromMemory();
  135. }
  136. }
  137. // Success! Functions in this SCC do not access memory, or only read memory.
  138. // Give them the appropriate attribute.
  139. bool MadeChange = false;
  140. for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
  141. Function *F = SCC[i]->getFunction();
  142. if (F->doesNotAccessMemory())
  143. // Already perfect!
  144. continue;
  145. if (F->onlyReadsMemory() && ReadsMemory)
  146. // No change.
  147. continue;
  148. MadeChange = true;
  149. // Clear out any existing attributes.
  150. F->removeAttribute(~0, Attribute::ReadOnly | Attribute::ReadNone);
  151. // Add in the new attribute.
  152. F->addAttribute(~0, ReadsMemory? Attribute::ReadOnly : Attribute::ReadNone);
  153. if (ReadsMemory)
  154. ++NumReadOnly;
  155. else
  156. ++NumReadNone;
  157. }
  158. return MadeChange;
  159. }
  160. /// AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
  161. bool FunctionAttrs::AddNoCaptureAttrs(const std::vector<CallGraphNode *> &SCC) {
  162. bool Changed = false;
  163. // Check each function in turn, determining which pointer arguments are not
  164. // captured.
  165. for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
  166. Function *F = SCC[i]->getFunction();
  167. if (F == 0)
  168. // External node - skip it;
  169. continue;
  170. // Definitions with weak linkage may be overridden at linktime with
  171. // something that writes memory, so treat them like declarations.
  172. if (F->isDeclaration() || F->mayBeOverridden())
  173. continue;
  174. for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A!=E; ++A)
  175. if (isa<PointerType>(A->getType()) && !A->hasNoCaptureAttr() &&
  176. !PointerMayBeCaptured(A, true)) {
  177. A->addAttr(Attribute::NoCapture);
  178. ++NumNoCapture;
  179. Changed = true;
  180. }
  181. }
  182. return Changed;
  183. }
  184. /// IsFunctionMallocLike - A function is malloc-like if it returns either null
  185. /// or a pointer that doesn't alias any other pointer visible to the caller.
  186. bool FunctionAttrs::IsFunctionMallocLike(Function *F,
  187. SmallPtrSet<Function*, 8> &SCCNodes) const {
  188. UniqueVector<Value *> FlowsToReturn;
  189. for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
  190. if (ReturnInst *Ret = dyn_cast<ReturnInst>(I->getTerminator()))
  191. FlowsToReturn.insert(Ret->getReturnValue());
  192. for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
  193. Value *RetVal = FlowsToReturn[i+1]; // UniqueVector[0] is reserved.
  194. if (Constant *C = dyn_cast<Constant>(RetVal)) {
  195. if (!C->isNullValue() && !isa<UndefValue>(C))
  196. return false;
  197. continue;
  198. }
  199. if (isa<Argument>(RetVal))
  200. return false;
  201. if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
  202. switch (RVI->getOpcode()) {
  203. // Extend the analysis by looking upwards.
  204. case Instruction::BitCast:
  205. case Instruction::GetElementPtr:
  206. FlowsToReturn.insert(RVI->getOperand(0));
  207. continue;
  208. case Instruction::Select: {
  209. SelectInst *SI = cast<SelectInst>(RVI);
  210. FlowsToReturn.insert(SI->getTrueValue());
  211. FlowsToReturn.insert(SI->getFalseValue());
  212. continue;
  213. }
  214. case Instruction::PHI: {
  215. PHINode *PN = cast<PHINode>(RVI);
  216. for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
  217. FlowsToReturn.insert(PN->getIncomingValue(i));
  218. continue;
  219. }
  220. // Check whether the pointer came from an allocation.
  221. case Instruction::Alloca:
  222. break;
  223. case Instruction::Call:
  224. case Instruction::Invoke: {
  225. CallSite CS(RVI);
  226. if (CS.paramHasAttr(0, Attribute::NoAlias))
  227. break;
  228. if (CS.getCalledFunction() &&
  229. SCCNodes.count(CS.getCalledFunction()))
  230. break;
  231. } // fall-through
  232. default:
  233. return false; // Did not come from an allocation.
  234. }
  235. if (PointerMayBeCaptured(RetVal, false))
  236. return false;
  237. }
  238. return true;
  239. }
  240. /// AddNoAliasAttrs - Deduce noalias attributes for the SCC.
  241. bool FunctionAttrs::AddNoAliasAttrs(const std::vector<CallGraphNode *> &SCC) {
  242. SmallPtrSet<Function*, 8> SCCNodes;
  243. // Fill SCCNodes with the elements of the SCC. Used for quickly
  244. // looking up whether a given CallGraphNode is in this SCC.
  245. for (unsigned i = 0, e = SCC.size(); i != e; ++i)
  246. SCCNodes.insert(SCC[i]->getFunction());
  247. // Check each function in turn, determining which functions return noalias
  248. // pointers.
  249. for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
  250. Function *F = SCC[i]->getFunction();
  251. if (F == 0)
  252. // External node - skip it;
  253. return false;
  254. // Already noalias.
  255. if (F->doesNotAlias(0))
  256. continue;
  257. // Definitions with weak linkage may be overridden at linktime, so
  258. // treat them like declarations.
  259. if (F->isDeclaration() || F->mayBeOverridden())
  260. return false;
  261. // We annotate noalias return values, which are only applicable to
  262. // pointer types.
  263. if (!isa<PointerType>(F->getReturnType()))
  264. continue;
  265. if (!IsFunctionMallocLike(F, SCCNodes))
  266. return false;
  267. }
  268. bool MadeChange = false;
  269. for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
  270. Function *F = SCC[i]->getFunction();
  271. if (F->doesNotAlias(0) || !isa<PointerType>(F->getReturnType()))
  272. continue;
  273. F->setDoesNotAlias(0);
  274. ++NumNoAlias;
  275. MadeChange = true;
  276. }
  277. return MadeChange;
  278. }
  279. bool FunctionAttrs::runOnSCC(std::vector<CallGraphNode *> &SCC) {
  280. bool Changed = AddReadAttrs(SCC);
  281. Changed |= AddNoCaptureAttrs(SCC);
  282. Changed |= AddNoAliasAttrs(SCC);
  283. return Changed;
  284. }