CaptureTracking.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. //===--- CaptureTracking.cpp - Determine whether a pointer is captured ----===//
  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 contains routines that help determine which pointers are captured.
  11. // A pointer value is captured if the function makes a copy of any part of the
  12. // pointer that outlives the call. Not being captured means, more or less, that
  13. // the pointer is only dereferenced and not stored in a global. Returning part
  14. // of the pointer as the function return value may or may not count as capturing
  15. // the pointer, depending on the context.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #include "llvm/ADT/SmallSet.h"
  19. #include "llvm/ADT/SmallVector.h"
  20. #include "llvm/Analysis/AliasAnalysis.h"
  21. #include "llvm/Analysis/CFG.h"
  22. #include "llvm/Analysis/CaptureTracking.h"
  23. #include "llvm/IR/CallSite.h"
  24. #include "llvm/IR/Constants.h"
  25. #include "llvm/IR/Dominators.h"
  26. #include "llvm/IR/Instructions.h"
  27. using namespace llvm;
  28. CaptureTracker::~CaptureTracker() {}
  29. bool CaptureTracker::shouldExplore(const Use *U) { return true; }
  30. namespace {
  31. struct SimpleCaptureTracker : public CaptureTracker {
  32. explicit SimpleCaptureTracker(bool ReturnCaptures)
  33. : ReturnCaptures(ReturnCaptures), Captured(false) {}
  34. void tooManyUses() override { Captured = true; }
  35. bool captured(const Use *U) override {
  36. if (isa<ReturnInst>(U->getUser()) && !ReturnCaptures)
  37. return false;
  38. Captured = true;
  39. return true;
  40. }
  41. bool ReturnCaptures;
  42. bool Captured;
  43. };
  44. /// Only find pointer captures which happen before the given instruction. Uses
  45. /// the dominator tree to determine whether one instruction is before another.
  46. /// Only support the case where the Value is defined in the same basic block
  47. /// as the given instruction and the use.
  48. struct CapturesBefore : public CaptureTracker {
  49. CapturesBefore(bool ReturnCaptures, const Instruction *I, DominatorTree *DT,
  50. bool IncludeI)
  51. : BeforeHere(I), DT(DT), ReturnCaptures(ReturnCaptures),
  52. IncludeI(IncludeI), Captured(false) {}
  53. void tooManyUses() override { Captured = true; }
  54. bool shouldExplore(const Use *U) override {
  55. Instruction *I = cast<Instruction>(U->getUser());
  56. if (BeforeHere == I && !IncludeI)
  57. return false;
  58. BasicBlock *BB = I->getParent();
  59. // We explore this usage only if the usage can reach "BeforeHere".
  60. // If use is not reachable from entry, there is no need to explore.
  61. if (BeforeHere != I && !DT->isReachableFromEntry(BB))
  62. return false;
  63. // If the value is defined in the same basic block as use and BeforeHere,
  64. // there is no need to explore the use if BeforeHere dominates use.
  65. // Check whether there is a path from I to BeforeHere.
  66. if (BeforeHere != I && DT->dominates(BeforeHere, I) &&
  67. !isPotentiallyReachable(I, BeforeHere, DT))
  68. return false;
  69. return true;
  70. }
  71. bool captured(const Use *U) override {
  72. if (isa<ReturnInst>(U->getUser()) && !ReturnCaptures)
  73. return false;
  74. Instruction *I = cast<Instruction>(U->getUser());
  75. if (BeforeHere == I && !IncludeI)
  76. return false;
  77. BasicBlock *BB = I->getParent();
  78. // Same logic as in shouldExplore.
  79. if (BeforeHere != I && !DT->isReachableFromEntry(BB))
  80. return false;
  81. if (BeforeHere != I && DT->dominates(BeforeHere, I) &&
  82. !isPotentiallyReachable(I, BeforeHere, DT))
  83. return false;
  84. Captured = true;
  85. return true;
  86. }
  87. const Instruction *BeforeHere;
  88. DominatorTree *DT;
  89. bool ReturnCaptures;
  90. bool IncludeI;
  91. bool Captured;
  92. };
  93. }
  94. /// PointerMayBeCaptured - Return true if this pointer value may be captured
  95. /// by the enclosing function (which is required to exist). This routine can
  96. /// be expensive, so consider caching the results. The boolean ReturnCaptures
  97. /// specifies whether returning the value (or part of it) from the function
  98. /// counts as capturing it or not. The boolean StoreCaptures specified whether
  99. /// storing the value (or part of it) into memory anywhere automatically
  100. /// counts as capturing it or not.
  101. bool llvm::PointerMayBeCaptured(const Value *V,
  102. bool ReturnCaptures, bool StoreCaptures) {
  103. assert(!isa<GlobalValue>(V) &&
  104. "It doesn't make sense to ask whether a global is captured.");
  105. // TODO: If StoreCaptures is not true, we could do Fancy analysis
  106. // to determine whether this store is not actually an escape point.
  107. // In that case, BasicAliasAnalysis should be updated as well to
  108. // take advantage of this.
  109. (void)StoreCaptures;
  110. SimpleCaptureTracker SCT(ReturnCaptures);
  111. PointerMayBeCaptured(V, &SCT);
  112. return SCT.Captured;
  113. }
  114. /// PointerMayBeCapturedBefore - Return true if this pointer value may be
  115. /// captured by the enclosing function (which is required to exist). If a
  116. /// DominatorTree is provided, only captures which happen before the given
  117. /// instruction are considered. This routine can be expensive, so consider
  118. /// caching the results. The boolean ReturnCaptures specifies whether
  119. /// returning the value (or part of it) from the function counts as capturing
  120. /// it or not. The boolean StoreCaptures specified whether storing the value
  121. /// (or part of it) into memory anywhere automatically counts as capturing it
  122. /// or not.
  123. bool llvm::PointerMayBeCapturedBefore(const Value *V, bool ReturnCaptures,
  124. bool StoreCaptures, const Instruction *I,
  125. DominatorTree *DT, bool IncludeI) {
  126. assert(!isa<GlobalValue>(V) &&
  127. "It doesn't make sense to ask whether a global is captured.");
  128. if (!DT)
  129. return PointerMayBeCaptured(V, ReturnCaptures, StoreCaptures);
  130. // TODO: See comment in PointerMayBeCaptured regarding what could be done
  131. // with StoreCaptures.
  132. CapturesBefore CB(ReturnCaptures, I, DT, IncludeI);
  133. PointerMayBeCaptured(V, &CB);
  134. return CB.Captured;
  135. }
  136. /// TODO: Write a new FunctionPass AliasAnalysis so that it can keep
  137. /// a cache. Then we can move the code from BasicAliasAnalysis into
  138. /// that path, and remove this threshold.
  139. static int const Threshold = 20;
  140. void llvm::PointerMayBeCaptured(const Value *V, CaptureTracker *Tracker) {
  141. assert(V->getType()->isPointerTy() && "Capture is for pointers only!");
  142. SmallVector<const Use *, Threshold> Worklist;
  143. SmallSet<const Use *, Threshold> Visited;
  144. int Count = 0;
  145. for (const Use &U : V->uses()) {
  146. // If there are lots of uses, conservatively say that the value
  147. // is captured to avoid taking too much compile time.
  148. if (Count++ >= Threshold)
  149. return Tracker->tooManyUses();
  150. if (!Tracker->shouldExplore(&U)) continue;
  151. Visited.insert(&U);
  152. Worklist.push_back(&U);
  153. }
  154. while (!Worklist.empty()) {
  155. const Use *U = Worklist.pop_back_val();
  156. Instruction *I = cast<Instruction>(U->getUser());
  157. V = U->get();
  158. switch (I->getOpcode()) {
  159. case Instruction::Call:
  160. case Instruction::Invoke: {
  161. CallSite CS(I);
  162. // Not captured if the callee is readonly, doesn't return a copy through
  163. // its return value and doesn't unwind (a readonly function can leak bits
  164. // by throwing an exception or not depending on the input value).
  165. if (CS.onlyReadsMemory() && CS.doesNotThrow() && I->getType()->isVoidTy())
  166. break;
  167. // Not captured if only passed via 'nocapture' arguments. Note that
  168. // calling a function pointer does not in itself cause the pointer to
  169. // be captured. This is a subtle point considering that (for example)
  170. // the callee might return its own address. It is analogous to saying
  171. // that loading a value from a pointer does not cause the pointer to be
  172. // captured, even though the loaded value might be the pointer itself
  173. // (think of self-referential objects).
  174. CallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end();
  175. for (CallSite::arg_iterator A = B; A != E; ++A)
  176. if (A->get() == V && !CS.doesNotCapture(A - B))
  177. // The parameter is not marked 'nocapture' - captured.
  178. if (Tracker->captured(U))
  179. return;
  180. break;
  181. }
  182. case Instruction::Load:
  183. // Loading from a pointer does not cause it to be captured.
  184. break;
  185. case Instruction::VAArg:
  186. // "va-arg" from a pointer does not cause it to be captured.
  187. break;
  188. case Instruction::Store:
  189. if (V == I->getOperand(0))
  190. // Stored the pointer - conservatively assume it may be captured.
  191. if (Tracker->captured(U))
  192. return;
  193. // Storing to the pointee does not cause the pointer to be captured.
  194. break;
  195. case Instruction::BitCast:
  196. case Instruction::GetElementPtr:
  197. case Instruction::PHI:
  198. case Instruction::Select:
  199. case Instruction::AddrSpaceCast:
  200. // The original value is not captured via this if the new value isn't.
  201. Count = 0;
  202. for (Use &UU : I->uses()) {
  203. // If there are lots of uses, conservatively say that the value
  204. // is captured to avoid taking too much compile time.
  205. if (Count++ >= Threshold)
  206. return Tracker->tooManyUses();
  207. if (Visited.insert(&UU).second)
  208. if (Tracker->shouldExplore(&UU))
  209. Worklist.push_back(&UU);
  210. }
  211. break;
  212. case Instruction::ICmp:
  213. // Don't count comparisons of a no-alias return value against null as
  214. // captures. This allows us to ignore comparisons of malloc results
  215. // with null, for example.
  216. if (ConstantPointerNull *CPN =
  217. dyn_cast<ConstantPointerNull>(I->getOperand(1)))
  218. if (CPN->getType()->getAddressSpace() == 0)
  219. if (isNoAliasCall(V->stripPointerCasts()))
  220. break;
  221. // Otherwise, be conservative. There are crazy ways to capture pointers
  222. // using comparisons.
  223. if (Tracker->captured(U))
  224. return;
  225. break;
  226. default:
  227. // Something else - be conservative and say it is captured.
  228. if (Tracker->captured(U))
  229. return;
  230. break;
  231. }
  232. }
  233. // All uses examined.
  234. }