LLVM 24.0.0git
AssumptionCache.h
Go to the documentation of this file.
1//===- llvm/Analysis/AssumptionCache.h - Track @llvm.assume -----*- C++ -*-===//
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 (allowing assumptions within any function to be
11// found cheaply by other parts of the optimizer).
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_ANALYSIS_ASSUMPTIONCACHE_H
16#define LLVM_ANALYSIS_ASSUMPTIONCACHE_H
17
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/DenseMap.h"
22#include "llvm/IR/PassManager.h"
23#include "llvm/IR/ValueHandle.h"
24#include "llvm/Pass.h"
26#include <memory>
27
28namespace llvm {
29
30struct AnalysisOptions;
31class AssumeInst;
32struct OperandBundleUse;
33class Function;
34class raw_ostream;
36class Value;
37
38/// A cache of \@llvm.assume calls within a function.
39///
40/// This cache provides fast lookup of assumptions within a function by caching
41/// them and amortizing the cost of scanning for them across all queries. Passes
42/// that create new assumptions are required to call registerAssumption() to
43/// register any new \@llvm.assume calls that they create. Deletions of
44/// \@llvm.assume calls do not require special handling.
46public:
47 /// Value of ResultElem::Index indicating that the argument to the call of the
48 /// llvm.assume.
49 enum : unsigned { ExprResultIdx = std::numeric_limits<unsigned>::max() };
50
51 struct ResultElem {
53
54 /// contains either ExprResultIdx or the index of the operand bundle
55 /// containing the knowledge.
56 unsigned Index;
57 operator Value *() const { return Assume; }
58 };
59
60private:
61 const AnalysisOptions &Opts;
62
63 /// The function for which this cache is handling assumptions.
64 ///
65 /// We track this to lazily populate our assumptions.
66 Function &F;
67
69
70 /// Vector of weak value handles to calls of the \@llvm.assume
71 /// intrinsic.
72 SmallVector<WeakVH, 4> AssumeHandles;
73
74 class LLVM_ABI AffectedValueCallbackVH final : public CallbackVH {
76
77 void deleted() override;
78 void allUsesReplacedWith(Value *) override;
79
80 public:
81 using DMI = DenseMapInfo<Value *>;
82
83 AffectedValueCallbackVH(Value *V, AssumptionCache *AC = nullptr)
84 : CallbackVH(V), AC(AC) {}
85 };
86
87 friend AffectedValueCallbackVH;
88
89 /// A map of values about which an assumption might be providing
90 /// information to the relevant set of assumptions.
91 using AffectedValuesMap =
92 DenseMap<AffectedValueCallbackVH, SmallVector<ResultElem, 1>,
93 AffectedValueCallbackVH::DMI>;
94 AffectedValuesMap AffectedValues;
95
96 /// Get the vector of assumptions which affect a value from the cache.
97 SmallVector<ResultElem, 1> &getOrInsertAffectedValues(Value *V);
98
99 /// Move affected values in the cache for OV to be affected values for NV.
100 void transferAffectedValuesInCache(Value *OV, Value *NV);
101
102 /// Remove the entries in the affected-values cache that point to \p CI.
103 void removeAffectedValues(AssumeInst *CI);
104
105 /// Flag tracking whether we have scanned the function yet.
106 ///
107 /// We want to be as lazy about this as possible, and so we scan the function
108 /// at the last moment.
109 bool Scanned = false;
110
111 /// Scan the function for assumptions and add them to the cache.
112 LLVM_ABI void scanFunction();
113
114public:
115 /// Construct an AssumptionCache from a function by scanning all of
116 /// its instructions.
117 LLVM_ABI AssumptionCache(Function &F, TargetTransformInfo *TTI = nullptr);
118
119 /// This cache is designed to be self-updating and so it should never be
120 /// invalidated.
122 FunctionAnalysisManager::Invalidator &) {
123 return false;
124 }
125
126 /// Add an \@llvm.assume intrinsic to this function's cache.
127 ///
128 /// The call passed in must be an instruction within this function and must
129 /// not already be in the cache.
131
132 /// Remove an \@llvm.assume intrinsic from this function's cache if it has
133 /// been added to the cache earlier.
135
136 /// Replace the assumption referenced by \p Handle (must be a valid handle for
137 /// a registered assumption) with \p New.
138 LLVM_ABI void replaceAssumption(WeakVH &Handle, AssumeInst *New);
139
140 /// Update the cache of values being affected by this assumption (i.e.
141 /// the values about which this assumption provides information).
143
144 /// Clear the cache of \@llvm.assume intrinsics for a function.
145 ///
146 /// It will be re-scanned the next time it is requested.
147 void clear() {
148 AssumeHandles.clear();
149 AffectedValues.clear();
150 Scanned = false;
151 }
152
153 /// Access the list of assumption handles currently tracked for this
154 /// function.
155 ///
156 /// Note that these produce weak handles that may be null. The caller must
157 /// handle that case.
158 /// FIXME: We should replace this with pointee_iterator<filter_iterator<...>>
159 /// when we can write that to filter out the null values. Then caller code
160 /// will become simpler.
162 if (!Scanned)
163 scanFunction();
164 return AssumeHandles;
165 }
166
167 /// Access the list of assumptions which affect this value.
168 ///
169 /// No more than -max-assumes-per-value of them are cached.
171 if (!Scanned)
172 scanFunction();
173
174 auto AVI = AffectedValues.find_as(const_cast<Value *>(V));
175 if (AVI == AffectedValues.end())
177
178 return AVI->second;
179 }
180
181 /// Determine which values are affected by this assume operand bundle.
182 LLVM_ABI static void
184 function_ref<void(Value *)> InsertAffected);
185};
186
187/// A function analysis which provides an \c AssumptionCache.
188///
189/// This analysis is intended for use with the new pass manager and will vend
190/// assumption caches for a given function.
191class AssumptionAnalysis : public AnalysisInfoMixin<AssumptionAnalysis> {
193
194 LLVM_ABI static AnalysisKey Key;
195
196public:
198
200};
201
202/// Printer pass for the \c AssumptionAnalysis results.
204 : public RequiredPassInfoMixin<AssumptionPrinterPass> {
205 raw_ostream &OS;
206
207public:
208 explicit AssumptionPrinterPass(raw_ostream &OS) : OS(OS) {}
209
211};
212
213/// An immutable pass that tracks lazily created \c AssumptionCache
214/// objects.
215///
216/// This is essentially a workaround for the legacy pass manager's weaknesses
217/// which associates each assumption cache with Function and clears it if the
218/// function is deleted. The nature of the AssumptionCache is that it is not
219/// invalidated by any changes to the function body and so this is sufficient
220/// to be conservatively correct.
222 /// A callback value handle applied to function objects, which we use to
223 /// delete our cache of intrinsics for a function when it is deleted.
224 class LLVM_ABI FunctionCallbackVH final : public CallbackVH {
226
227 void deleted() override;
228
229 public:
230 using DMI = DenseMapInfo<Value *>;
231
232 FunctionCallbackVH(Value *V, AssumptionCacheTracker *ACT = nullptr)
233 : CallbackVH(V), ACT(ACT) {}
234 };
235
236 friend FunctionCallbackVH;
237
238 using FunctionCallsMap =
240 FunctionCallbackVH::DMI>;
241
242 FunctionCallsMap AssumptionCaches;
243
244public:
245 /// Get the cached assumptions for a function.
246 ///
247 /// If no assumptions are cached, this will scan the function. Otherwise, the
248 /// existing cache will be returned.
250
253
254 void releaseMemory() override {
256 AssumptionCaches.shrink_and_clear();
257 }
258
259 void verifyAnalysis() const override;
260
261 bool doFinalization(Module &) override {
263 return false;
264 }
265
266 static char ID; // Pass identification, replacement for typeid
267};
268
269template<> struct simplify_type<AssumptionCache::ResultElem> {
270 using SimpleType = Value *;
271
273 return Val;
274 }
275};
276template<> struct simplify_type<const AssumptionCache::ResultElem> {
277 using SimpleType = /*const*/ Value *;
278
280 return Val;
281 }
282};
283
284} // end namespace llvm
285
286#endif // LLVM_ANALYSIS_ASSUMPTIONCACHE_H
aarch64 promote const
#define LLVM_ABI
Definition Compiler.h:211
This file defines DenseMapInfo traits for DenseMap.
This file defines the DenseMap class.
This header defines various interfaces for pass management in LLVM.
#define F(x, y, z)
Definition MD5.cpp:54
This file defines the SmallVector class.
This represents the llvm.assume intrinsic.
A function analysis which provides an AssumptionCache.
LLVM_ABI AssumptionCache run(Function &F, FunctionAnalysisManager &)
bool doFinalization(Module &) override
doFinalization - Virtual method overriden by subclasses to do any necessary clean up after all passes...
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
void verifyAnalysis() const override
verifyAnalysis() - This member can be implemented by a analysis pass to check state of analysis infor...
AssumptionCache & getAssumptionCache(Function &F)
Get the cached assumptions for a function.
A cache of @llvm.assume calls within a function.
static LLVM_ABI void findValuesAffectedByOperandBundle(OperandBundleUse Bundle, function_ref< void(Value *)> InsertAffected)
Determine which values are affected by this assume operand bundle.
LLVM_ABI void registerAssumption(AssumeInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
void clear()
Clear the cache of @llvm.assume intrinsics for a function.
LLVM_ABI void replaceAssumption(WeakVH &Handle, AssumeInst *New)
Replace the assumption referenced by Handle (must be a valid handle for a registered assumption) with...
bool invalidate(Function &, const PreservedAnalyses &, FunctionAnalysisManager::Invalidator &)
This cache is designed to be self-updating and so it should never be invalidated.
LLVM_ABI void updateAffectedValues(AssumeInst *CI)
Update the cache of values being affected by this assumption (i.e.
MutableArrayRef< WeakVH > assumptions()
Access the list of assumption handles currently tracked for this function.
LLVM_ABI void unregisterAssumption(AssumeInst *CI)
Remove an @llvm.assume intrinsic from this function's cache if it has been added to the cache earlier...
LLVM_ABI AssumptionCache(Function &F, TargetTransformInfo *TTI=nullptr)
Construct an AssumptionCache from a function by scanning all of its instructions.
MutableArrayRef< ResultElem > assumptionsFor(const Value *V)
Access the list of assumptions which affect this value.
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
AssumptionPrinterPass(raw_ostream &OS)
Value handle with callbacks on RAUW and destruction.
ImmutablePass(char &pid)
Definition Pass.h:285
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
LLVM Value Representation.
Definition Value.h:75
A nullable Value handle that is nullable.
An efficient, type-erasing, non-owning reference to a callable.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
This is an optimization pass for GlobalISel generic memory operations.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
TargetTransformInfo TTI
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
A CRTP mix-in that provides informational APIs needed for analysis passes.
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
unsigned Index
contains either ExprResultIdx or the index of the operand bundle containing the knowledge.
An information struct used to provide DenseMap with the various necessary components for a given valu...
A lightweight accessor for an operand bundle meant to be passed around by value.
A CRTP mix-in for passes that should not be skipped.
static SimpleType getSimplifiedValue(AssumptionCache::ResultElem &Val)
static SimpleType getSimplifiedValue(const AssumptionCache::ResultElem &Val)
Define a template that can be specialized by smart pointers to reflect the fact that they are automat...
Definition Casting.h:34