AssumptionCache.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. //===- AssumptionCache.cpp - Cache finding @llvm.assume calls -------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file contains a pass that keeps track of @llvm.assume intrinsics in
  10. // the functions of a module.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Analysis/AssumeBundleQueries.h"
  14. #include "llvm/Analysis/AssumptionCache.h"
  15. #include "llvm/ADT/STLExtras.h"
  16. #include "llvm/ADT/SmallPtrSet.h"
  17. #include "llvm/ADT/SmallVector.h"
  18. #include "llvm/Analysis/TargetTransformInfo.h"
  19. #include "llvm/IR/BasicBlock.h"
  20. #include "llvm/IR/Function.h"
  21. #include "llvm/IR/InstrTypes.h"
  22. #include "llvm/IR/Instruction.h"
  23. #include "llvm/IR/Instructions.h"
  24. #include "llvm/IR/Intrinsics.h"
  25. #include "llvm/IR/PassManager.h"
  26. #include "llvm/IR/PatternMatch.h"
  27. #include "llvm/InitializePasses.h"
  28. #include "llvm/Pass.h"
  29. #include "llvm/Support/Casting.h"
  30. #include "llvm/Support/CommandLine.h"
  31. #include "llvm/Support/ErrorHandling.h"
  32. #include "llvm/Support/raw_ostream.h"
  33. #include <algorithm>
  34. #include <cassert>
  35. #include <utility>
  36. using namespace llvm;
  37. using namespace llvm::PatternMatch;
  38. static cl::opt<bool>
  39. VerifyAssumptionCache("verify-assumption-cache", cl::Hidden,
  40. cl::desc("Enable verification of assumption cache"),
  41. cl::init(false));
  42. SmallVector<AssumptionCache::ResultElem, 1> &
  43. AssumptionCache::getOrInsertAffectedValues(Value *V) {
  44. // Try using find_as first to avoid creating extra value handles just for the
  45. // purpose of doing the lookup.
  46. auto AVI = AffectedValues.find_as(V);
  47. if (AVI != AffectedValues.end())
  48. return AVI->second;
  49. auto AVIP = AffectedValues.insert(
  50. {AffectedValueCallbackVH(V, this), SmallVector<ResultElem, 1>()});
  51. return AVIP.first->second;
  52. }
  53. static void
  54. findAffectedValues(CallBase *CI, TargetTransformInfo *TTI,
  55. SmallVectorImpl<AssumptionCache::ResultElem> &Affected) {
  56. // Note: This code must be kept in-sync with the code in
  57. // computeKnownBitsFromAssume in ValueTracking.
  58. auto AddAffected = [&Affected](Value *V, unsigned Idx =
  59. AssumptionCache::ExprResultIdx) {
  60. if (isa<Argument>(V)) {
  61. Affected.push_back({V, Idx});
  62. } else if (auto *I = dyn_cast<Instruction>(V)) {
  63. Affected.push_back({I, Idx});
  64. // Peek through unary operators to find the source of the condition.
  65. Value *Op;
  66. if (match(I, m_BitCast(m_Value(Op))) ||
  67. match(I, m_PtrToInt(m_Value(Op))) || match(I, m_Not(m_Value(Op)))) {
  68. if (isa<Instruction>(Op) || isa<Argument>(Op))
  69. Affected.push_back({Op, Idx});
  70. }
  71. }
  72. };
  73. for (unsigned Idx = 0; Idx != CI->getNumOperandBundles(); Idx++) {
  74. if (CI->getOperandBundleAt(Idx).Inputs.size() > ABA_WasOn &&
  75. CI->getOperandBundleAt(Idx).getTagName() != IgnoreBundleTag)
  76. AddAffected(CI->getOperandBundleAt(Idx).Inputs[ABA_WasOn], Idx);
  77. }
  78. Value *Cond = CI->getArgOperand(0), *A, *B;
  79. AddAffected(Cond);
  80. CmpInst::Predicate Pred;
  81. if (match(Cond, m_ICmp(Pred, m_Value(A), m_Value(B)))) {
  82. AddAffected(A);
  83. AddAffected(B);
  84. if (Pred == ICmpInst::ICMP_EQ) {
  85. // For equality comparisons, we handle the case of bit inversion.
  86. auto AddAffectedFromEq = [&AddAffected](Value *V) {
  87. Value *A;
  88. if (match(V, m_Not(m_Value(A)))) {
  89. AddAffected(A);
  90. V = A;
  91. }
  92. Value *B;
  93. // (A & B) or (A | B) or (A ^ B).
  94. if (match(V, m_BitwiseLogic(m_Value(A), m_Value(B)))) {
  95. AddAffected(A);
  96. AddAffected(B);
  97. // (A << C) or (A >>_s C) or (A >>_u C) where C is some constant.
  98. } else if (match(V, m_Shift(m_Value(A), m_ConstantInt()))) {
  99. AddAffected(A);
  100. }
  101. };
  102. AddAffectedFromEq(A);
  103. AddAffectedFromEq(B);
  104. }
  105. Value *X;
  106. // Handle (A + C1) u< C2, which is the canonical form of A > C3 && A < C4,
  107. // and recognized by LVI at least.
  108. if (Pred == ICmpInst::ICMP_ULT &&
  109. match(A, m_Add(m_Value(X), m_ConstantInt())) &&
  110. match(B, m_ConstantInt()))
  111. AddAffected(X);
  112. }
  113. if (TTI) {
  114. const Value *Ptr;
  115. unsigned AS;
  116. std::tie(Ptr, AS) = TTI->getPredicatedAddrSpace(Cond);
  117. if (Ptr)
  118. AddAffected(const_cast<Value *>(Ptr->stripInBoundsOffsets()));
  119. }
  120. }
  121. void AssumptionCache::updateAffectedValues(AssumeInst *CI) {
  122. SmallVector<AssumptionCache::ResultElem, 16> Affected;
  123. findAffectedValues(CI, TTI, Affected);
  124. for (auto &AV : Affected) {
  125. auto &AVV = getOrInsertAffectedValues(AV.Assume);
  126. if (llvm::none_of(AVV, [&](ResultElem &Elem) {
  127. return Elem.Assume == CI && Elem.Index == AV.Index;
  128. }))
  129. AVV.push_back({CI, AV.Index});
  130. }
  131. }
  132. void AssumptionCache::unregisterAssumption(AssumeInst *CI) {
  133. SmallVector<AssumptionCache::ResultElem, 16> Affected;
  134. findAffectedValues(CI, TTI, Affected);
  135. for (auto &AV : Affected) {
  136. auto AVI = AffectedValues.find_as(AV.Assume);
  137. if (AVI == AffectedValues.end())
  138. continue;
  139. bool Found = false;
  140. bool HasNonnull = false;
  141. for (ResultElem &Elem : AVI->second) {
  142. if (Elem.Assume == CI) {
  143. Found = true;
  144. Elem.Assume = nullptr;
  145. }
  146. HasNonnull |= !!Elem.Assume;
  147. if (HasNonnull && Found)
  148. break;
  149. }
  150. assert(Found && "already unregistered or incorrect cache state");
  151. if (!HasNonnull)
  152. AffectedValues.erase(AVI);
  153. }
  154. erase_value(AssumeHandles, CI);
  155. }
  156. void AssumptionCache::AffectedValueCallbackVH::deleted() {
  157. AC->AffectedValues.erase(getValPtr());
  158. // 'this' now dangles!
  159. }
  160. void AssumptionCache::transferAffectedValuesInCache(Value *OV, Value *NV) {
  161. auto &NAVV = getOrInsertAffectedValues(NV);
  162. auto AVI = AffectedValues.find(OV);
  163. if (AVI == AffectedValues.end())
  164. return;
  165. for (auto &A : AVI->second)
  166. if (!llvm::is_contained(NAVV, A))
  167. NAVV.push_back(A);
  168. AffectedValues.erase(OV);
  169. }
  170. void AssumptionCache::AffectedValueCallbackVH::allUsesReplacedWith(Value *NV) {
  171. if (!isa<Instruction>(NV) && !isa<Argument>(NV))
  172. return;
  173. // Any assumptions that affected this value now affect the new value.
  174. AC->transferAffectedValuesInCache(getValPtr(), NV);
  175. // 'this' now might dangle! If the AffectedValues map was resized to add an
  176. // entry for NV then this object might have been destroyed in favor of some
  177. // copy in the grown map.
  178. }
  179. void AssumptionCache::scanFunction() {
  180. assert(!Scanned && "Tried to scan the function twice!");
  181. assert(AssumeHandles.empty() && "Already have assumes when scanning!");
  182. // Go through all instructions in all blocks, add all calls to @llvm.assume
  183. // to this cache.
  184. for (BasicBlock &B : F)
  185. for (Instruction &I : B)
  186. if (isa<AssumeInst>(&I))
  187. AssumeHandles.push_back({&I, ExprResultIdx});
  188. // Mark the scan as complete.
  189. Scanned = true;
  190. // Update affected values.
  191. for (auto &A : AssumeHandles)
  192. updateAffectedValues(cast<AssumeInst>(A));
  193. }
  194. void AssumptionCache::registerAssumption(AssumeInst *CI) {
  195. // If we haven't scanned the function yet, just drop this assumption. It will
  196. // be found when we scan later.
  197. if (!Scanned)
  198. return;
  199. AssumeHandles.push_back({CI, ExprResultIdx});
  200. #ifndef NDEBUG
  201. assert(CI->getParent() &&
  202. "Cannot register @llvm.assume call not in a basic block");
  203. assert(&F == CI->getParent()->getParent() &&
  204. "Cannot register @llvm.assume call not in this function");
  205. // We expect the number of assumptions to be small, so in an asserts build
  206. // check that we don't accumulate duplicates and that all assumptions point
  207. // to the same function.
  208. SmallPtrSet<Value *, 16> AssumptionSet;
  209. for (auto &VH : AssumeHandles) {
  210. if (!VH)
  211. continue;
  212. assert(&F == cast<Instruction>(VH)->getParent()->getParent() &&
  213. "Cached assumption not inside this function!");
  214. assert(match(cast<CallInst>(VH), m_Intrinsic<Intrinsic::assume>()) &&
  215. "Cached something other than a call to @llvm.assume!");
  216. assert(AssumptionSet.insert(VH).second &&
  217. "Cache contains multiple copies of a call!");
  218. }
  219. #endif
  220. updateAffectedValues(CI);
  221. }
  222. AssumptionCache AssumptionAnalysis::run(Function &F,
  223. FunctionAnalysisManager &FAM) {
  224. auto &TTI = FAM.getResult<TargetIRAnalysis>(F);
  225. return AssumptionCache(F, &TTI);
  226. }
  227. AnalysisKey AssumptionAnalysis::Key;
  228. PreservedAnalyses AssumptionPrinterPass::run(Function &F,
  229. FunctionAnalysisManager &AM) {
  230. AssumptionCache &AC = AM.getResult<AssumptionAnalysis>(F);
  231. OS << "Cached assumptions for function: " << F.getName() << "\n";
  232. for (auto &VH : AC.assumptions())
  233. if (VH)
  234. OS << " " << *cast<CallInst>(VH)->getArgOperand(0) << "\n";
  235. return PreservedAnalyses::all();
  236. }
  237. void AssumptionCacheTracker::FunctionCallbackVH::deleted() {
  238. auto I = ACT->AssumptionCaches.find_as(cast<Function>(getValPtr()));
  239. if (I != ACT->AssumptionCaches.end())
  240. ACT->AssumptionCaches.erase(I);
  241. // 'this' now dangles!
  242. }
  243. AssumptionCache &AssumptionCacheTracker::getAssumptionCache(Function &F) {
  244. // We probe the function map twice to try and avoid creating a value handle
  245. // around the function in common cases. This makes insertion a bit slower,
  246. // but if we have to insert we're going to scan the whole function so that
  247. // shouldn't matter.
  248. auto I = AssumptionCaches.find_as(&F);
  249. if (I != AssumptionCaches.end())
  250. return *I->second;
  251. auto *TTIWP = getAnalysisIfAvailable<TargetTransformInfoWrapperPass>();
  252. auto *TTI = TTIWP ? &TTIWP->getTTI(F) : nullptr;
  253. // Ok, build a new cache by scanning the function, insert it and the value
  254. // handle into our map, and return the newly populated cache.
  255. auto IP = AssumptionCaches.insert(std::make_pair(
  256. FunctionCallbackVH(&F, this), std::make_unique<AssumptionCache>(F, TTI)));
  257. assert(IP.second && "Scanning function already in the map?");
  258. return *IP.first->second;
  259. }
  260. AssumptionCache *AssumptionCacheTracker::lookupAssumptionCache(Function &F) {
  261. auto I = AssumptionCaches.find_as(&F);
  262. if (I != AssumptionCaches.end())
  263. return I->second.get();
  264. return nullptr;
  265. }
  266. void AssumptionCacheTracker::verifyAnalysis() const {
  267. // FIXME: In the long term the verifier should not be controllable with a
  268. // flag. We should either fix all passes to correctly update the assumption
  269. // cache and enable the verifier unconditionally or somehow arrange for the
  270. // assumption list to be updated automatically by passes.
  271. if (!VerifyAssumptionCache)
  272. return;
  273. SmallPtrSet<const CallInst *, 4> AssumptionSet;
  274. for (const auto &I : AssumptionCaches) {
  275. for (auto &VH : I.second->assumptions())
  276. if (VH)
  277. AssumptionSet.insert(cast<CallInst>(VH));
  278. for (const BasicBlock &B : cast<Function>(*I.first))
  279. for (const Instruction &II : B)
  280. if (match(&II, m_Intrinsic<Intrinsic::assume>()) &&
  281. !AssumptionSet.count(cast<CallInst>(&II)))
  282. report_fatal_error("Assumption in scanned function not in cache");
  283. }
  284. }
  285. AssumptionCacheTracker::AssumptionCacheTracker() : ImmutablePass(ID) {
  286. initializeAssumptionCacheTrackerPass(*PassRegistry::getPassRegistry());
  287. }
  288. AssumptionCacheTracker::~AssumptionCacheTracker() = default;
  289. char AssumptionCacheTracker::ID = 0;
  290. INITIALIZE_PASS(AssumptionCacheTracker, "assumption-cache-tracker",
  291. "Assumption Cache Tracker", false, true)