LLVM 20.0.0git
MemoryLocation.h
Go to the documentation of this file.
1//===- MemoryLocation.h - Memory location descriptions ----------*- 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/// \file
9/// This file provides utility analysis objects describing memory locations.
10/// These are used both by the Alias Analysis infrastructure and more
11/// specialized memory analysis layers.
12///
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_ANALYSIS_MEMORYLOCATION_H
16#define LLVM_ANALYSIS_MEMORYLOCATION_H
17
19#include "llvm/IR/Metadata.h"
21
22#include <optional>
23
24namespace llvm {
25
26class CallBase;
27class Instruction;
28class LoadInst;
29class StoreInst;
30class MemTransferInst;
31class MemIntrinsic;
32class AtomicCmpXchgInst;
33class AtomicMemTransferInst;
34class AtomicMemIntrinsic;
35class AtomicRMWInst;
36class AnyMemTransferInst;
37class AnyMemIntrinsic;
38class TargetLibraryInfo;
39class VAArgInst;
40
41// Represents the size of a MemoryLocation. Logically, it's an
42// std::optional<uint63_t> that also carries a bit to represent whether the
43// integer it contains, N, is 'precise'. Precise, in this context, means that we
44// know that the area of storage referenced by the given MemoryLocation must be
45// precisely N bytes. An imprecise value is formed as the union of two or more
46// precise values, and can conservatively represent all of the values unioned
47// into it. Importantly, imprecise values are an *upper-bound* on the size of a
48// MemoryLocation.
49//
50// Concretely, a precise MemoryLocation is (%p, 4) in
51// store i32 0, i32* %p
52//
53// Since we know that %p must be at least 4 bytes large at this point.
54// Otherwise, we have UB. An example of an imprecise MemoryLocation is (%p, 4)
55// at the memcpy in
56//
57// %n = select i1 %foo, i64 1, i64 4
58// call void @llvm.memcpy.p0i8.p0i8.i64(i8* %p, i8* %baz, i64 %n, i32 1,
59// i1 false)
60//
61// ...Since we'll copy *up to* 4 bytes into %p, but we can't guarantee that
62// we'll ever actually do so.
63//
64// If asked to represent a pathologically large value, this will degrade to
65// std::nullopt.
66// Store Scalable information in bit 62 of Value. Scalable information is
67// required to do Alias Analysis on Scalable quantities
69 enum : uint64_t {
70 BeforeOrAfterPointer = ~uint64_t(0),
71 ScalableBit = uint64_t(1) << 62,
72 AfterPointer = (BeforeOrAfterPointer - 1) & ~ScalableBit,
73 MapEmpty = BeforeOrAfterPointer - 2,
74 MapTombstone = BeforeOrAfterPointer - 3,
75 ImpreciseBit = uint64_t(1) << 63,
76
77 // The maximum value we can represent without falling back to 'unknown'.
78 MaxValue = (MapTombstone - 1) & ~(ImpreciseBit | ScalableBit),
79 };
80
82
83 // Hack to support implicit construction. This should disappear when the
84 // public LocationSize ctor goes away.
85 enum DirectConstruction { Direct };
86
87 constexpr LocationSize(uint64_t Raw, DirectConstruction) : Value(Raw) {}
88 constexpr LocationSize(uint64_t Raw, bool Scalable)
89 : Value(Raw > MaxValue ? AfterPointer
90 : Raw | (Scalable ? ScalableBit : uint64_t(0))) {}
91
92 static_assert(AfterPointer & ImpreciseBit,
93 "AfterPointer is imprecise by definition.");
94 static_assert(BeforeOrAfterPointer & ImpreciseBit,
95 "BeforeOrAfterPointer is imprecise by definition.");
96 static_assert(~(MaxValue & ScalableBit), "Max value don't have bit 62 set");
97
98public:
99 // FIXME: Migrate all users to construct via either `precise` or `upperBound`,
100 // to make it more obvious at the callsite the kind of size that they're
101 // providing.
102 //
103 // Since the overwhelming majority of users of this provide precise values,
104 // this assumes the provided value is precise.
105 constexpr LocationSize(uint64_t Raw)
106 : Value(Raw > MaxValue ? AfterPointer : Raw) {}
107 // Create non-scalable LocationSize
109 return LocationSize(Value, false /*Scalable*/);
110 }
112 return LocationSize(Value.getKnownMinValue(), Value.isScalable());
113 }
114
116 // You can't go lower than 0, so give a precise result.
117 if (LLVM_UNLIKELY(Value == 0))
118 return precise(0);
119 if (LLVM_UNLIKELY(Value > MaxValue))
120 return afterPointer();
121 return LocationSize(Value | ImpreciseBit, Direct);
122 }
124 if (Value.isScalable())
125 return afterPointer();
126 return upperBound(Value.getFixedValue());
127 }
128
129 /// Any location after the base pointer (but still within the underlying
130 /// object).
131 constexpr static LocationSize afterPointer() {
132 return LocationSize(AfterPointer, Direct);
133 }
134
135 /// Any location before or after the base pointer (but still within the
136 /// underlying object).
138 return LocationSize(BeforeOrAfterPointer, Direct);
139 }
140
141 // Sentinel values, generally used for maps.
142 constexpr static LocationSize mapTombstone() {
143 return LocationSize(MapTombstone, Direct);
144 }
145 constexpr static LocationSize mapEmpty() {
146 return LocationSize(MapEmpty, Direct);
147 }
148
149 // Returns a LocationSize that can correctly represent either `*this` or
150 // `Other`.
152 if (Other == *this)
153 return *this;
154
155 if (Value == BeforeOrAfterPointer || Other.Value == BeforeOrAfterPointer)
156 return beforeOrAfterPointer();
157 if (Value == AfterPointer || Other.Value == AfterPointer)
158 return afterPointer();
159 if (isScalable() || Other.isScalable())
160 return afterPointer();
161
162 return upperBound(std::max(getValue(), Other.getValue()));
163 }
164
165 bool hasValue() const {
166 return Value != AfterPointer && Value != BeforeOrAfterPointer;
167 }
168 bool isScalable() const { return (Value & ScalableBit); }
169
171 assert(hasValue() && "Getting value from an unknown LocationSize!");
172 assert((Value & ~(ImpreciseBit | ScalableBit)) < MaxValue &&
173 "Scalable bit of value should be masked");
174 return {Value & ~(ImpreciseBit | ScalableBit), isScalable()};
175 }
176
177 // Returns whether or not this value is precise. Note that if a value is
178 // precise, it's guaranteed to not be unknown.
179 bool isPrecise() const { return (Value & ImpreciseBit) == 0; }
180
181 // Convenience method to check if this LocationSize's value is 0.
182 bool isZero() const {
183 return hasValue() && getValue().getKnownMinValue() == 0;
184 }
185
186 /// Whether accesses before the base pointer are possible.
187 bool mayBeBeforePointer() const { return Value == BeforeOrAfterPointer; }
188
189 bool operator==(const LocationSize &Other) const {
190 return Value == Other.Value;
191 }
192
193 bool operator==(const TypeSize &Other) const {
194 return hasValue() && getValue() == Other;
195 }
196
197 bool operator!=(const LocationSize &Other) const { return !(*this == Other); }
198
199 bool operator!=(const TypeSize &Other) const { return !(*this == Other); }
200
201 // Ordering operators are not provided, since it's unclear if there's only one
202 // reasonable way to compare:
203 // - values that don't exist against values that do, and
204 // - precise values to imprecise values
205
206 void print(raw_ostream &OS) const;
207
208 // Returns an opaque value that represents this LocationSize. Cannot be
209 // reliably converted back into a LocationSize.
210 uint64_t toRaw() const { return Value; }
211};
212
214 Size.print(OS);
215 return OS;
216}
217
218/// Representation for a specific memory location.
219///
220/// This abstraction can be used to represent a specific location in memory.
221/// The goal of the location is to represent enough information to describe
222/// abstract aliasing, modification, and reference behaviors of whatever
223/// value(s) are stored in memory at the particular location.
224///
225/// The primary user of this interface is LLVM's Alias Analysis, but other
226/// memory analyses such as MemoryDependence can use it as well.
228public:
229 /// UnknownSize - This is a special value which can be used with the
230 /// size arguments in alias queries to indicate that the caller does not
231 /// know the sizes of the potential memory references.
232 enum : uint64_t { UnknownSize = ~UINT64_C(0) };
233
234 /// The address of the start of the location.
235 const Value *Ptr;
236
237 /// The maximum size of the location, in address-units, or
238 /// UnknownSize if the size is not known.
239 ///
240 /// Note that an unknown size does not mean the pointer aliases the entire
241 /// virtual address space, because there are restrictions on stepping out of
242 /// one object and into another. See
243 /// http://llvm.org/docs/LangRef.html#pointeraliasing
245
246 /// The metadata nodes which describes the aliasing of the location (each
247 /// member is null if that kind of information is unavailable).
249
250 void print(raw_ostream &OS) const { OS << *Ptr << " " << Size << "\n"; }
251
252 /// Return a location with information about the memory reference by the given
253 /// instruction.
254 static MemoryLocation get(const LoadInst *LI);
255 static MemoryLocation get(const StoreInst *SI);
256 static MemoryLocation get(const VAArgInst *VI);
257 static MemoryLocation get(const AtomicCmpXchgInst *CXI);
258 static MemoryLocation get(const AtomicRMWInst *RMWI);
259 static MemoryLocation get(const Instruction *Inst) {
260 return *MemoryLocation::getOrNone(Inst);
261 }
262 static std::optional<MemoryLocation> getOrNone(const Instruction *Inst);
263
264 /// Return a location representing the source of a memory transfer.
268
269 /// Return a location representing the destination of a memory set or
270 /// transfer.
274 static std::optional<MemoryLocation> getForDest(const CallBase *CI,
275 const TargetLibraryInfo &TLI);
276
277 /// Return a location representing a particular argument of a call.
278 static MemoryLocation getForArgument(const CallBase *Call, unsigned ArgIdx,
279 const TargetLibraryInfo *TLI);
280 static MemoryLocation getForArgument(const CallBase *Call, unsigned ArgIdx,
281 const TargetLibraryInfo &TLI) {
282 return getForArgument(Call, ArgIdx, &TLI);
283 }
284
285 /// Return a location that may access any location after Ptr, while remaining
286 /// within the underlying object.
288 const AAMDNodes &AATags = AAMDNodes()) {
290 }
291
292 /// Return a location that may access any location before or after Ptr, while
293 /// remaining within the underlying object.
294 static MemoryLocation
297 }
298
299 MemoryLocation() : Ptr(nullptr), Size(LocationSize::beforeOrAfterPointer()) {}
300
302 const AAMDNodes &AATags = AAMDNodes())
303 : Ptr(Ptr), Size(Size), AATags(AATags) {}
304
305 MemoryLocation getWithNewPtr(const Value *NewPtr) const {
306 MemoryLocation Copy(*this);
307 Copy.Ptr = NewPtr;
308 return Copy;
309 }
310
312 MemoryLocation Copy(*this);
313 Copy.Size = NewSize;
314 return Copy;
315 }
316
318 MemoryLocation Copy(*this);
319 Copy.AATags = AAMDNodes();
320 return Copy;
321 }
322
323 bool operator==(const MemoryLocation &Other) const {
324 return Ptr == Other.Ptr && Size == Other.Size && AATags == Other.AATags;
325 }
326};
327
328// Specialize DenseMapInfo.
329template <> struct DenseMapInfo<LocationSize> {
330 static inline LocationSize getEmptyKey() { return LocationSize::mapEmpty(); }
333 }
334 static unsigned getHashValue(const LocationSize &Val) {
336 }
337 static bool isEqual(const LocationSize &LHS, const LocationSize &RHS) {
338 return LHS == RHS;
339 }
340};
341
342template <> struct DenseMapInfo<MemoryLocation> {
343 static inline MemoryLocation getEmptyKey() {
346 }
350 }
351 static unsigned getHashValue(const MemoryLocation &Val) {
355 }
356 static bool isEqual(const MemoryLocation &LHS, const MemoryLocation &RHS) {
357 return LHS == RHS;
358 }
359};
360} // namespace llvm
361
362#endif
#define LLVM_UNLIKELY(EXPR)
Definition: Compiler.h:320
This file defines DenseMapInfo traits for DenseMap.
uint64_t Size
IRTranslator LLVM IR MI
This file contains the declarations for metadata subclasses.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
raw_pwrite_stream & OS
Value * RHS
Value * LHS
An instruction that atomically checks whether a specified value is in a memory location,...
Definition: Instructions.h:501
an instruction that atomically reads a memory location, combines it with another value,...
Definition: Instructions.h:704
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Definition: InstrTypes.h:1120
An instruction for reading from memory.
Definition: Instructions.h:176
bool hasValue() const
static LocationSize precise(uint64_t Value)
static constexpr LocationSize mapEmpty()
static LocationSize upperBound(TypeSize Value)
bool mayBeBeforePointer() const
Whether accesses before the base pointer are possible.
bool operator==(const TypeSize &Other) const
static constexpr LocationSize beforeOrAfterPointer()
Any location before or after the base pointer (but still within the underlying object).
bool isScalable() const
TypeSize getValue() const
bool isZero() const
void print(raw_ostream &OS) const
bool operator!=(const TypeSize &Other) const
bool isPrecise() const
bool operator!=(const LocationSize &Other) const
static constexpr LocationSize afterPointer()
Any location after the base pointer (but still within the underlying object).
uint64_t toRaw() const
LocationSize unionWith(LocationSize Other) const
static LocationSize upperBound(uint64_t Value)
constexpr LocationSize(uint64_t Raw)
static constexpr LocationSize mapTombstone()
bool operator==(const LocationSize &Other) const
static LocationSize precise(TypeSize Value)
This is the common base class for memset/memcpy/memmove.
This class wraps the llvm.memcpy/memmove intrinsics.
Representation for a specific memory location.
MemoryLocation getWithNewSize(LocationSize NewSize) const
MemoryLocation getWithoutAATags() const
static MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
static MemoryLocation getForArgument(const CallBase *Call, unsigned ArgIdx, const TargetLibraryInfo &TLI)
static MemoryLocation getForSource(const MemTransferInst *MTI)
Return a location representing the source of a memory transfer.
void print(raw_ostream &OS) const
LocationSize Size
The maximum size of the location, in address-units, or UnknownSize if the size is not known.
static MemoryLocation getBeforeOrAfter(const Value *Ptr, const AAMDNodes &AATags=AAMDNodes())
Return a location that may access any location before or after Ptr, while remaining within the underl...
static MemoryLocation getAfter(const Value *Ptr, const AAMDNodes &AATags=AAMDNodes())
Return a location that may access any location after Ptr, while remaining within the underlying objec...
static MemoryLocation get(const Instruction *Inst)
MemoryLocation getWithNewPtr(const Value *NewPtr) const
AAMDNodes AATags
The metadata nodes which describes the aliasing of the location (each member is null if that kind of ...
const Value * Ptr
The address of the start of the location.
MemoryLocation(const Value *Ptr, LocationSize Size, const AAMDNodes &AATags=AAMDNodes())
static MemoryLocation getForDest(const MemIntrinsic *MI)
Return a location representing the destination of a memory set or transfer.
bool operator==(const MemoryLocation &Other) const
static std::optional< MemoryLocation > getOrNone(const Instruction *Inst)
static MemoryLocation getForArgument(const CallBase *Call, unsigned ArgIdx, const TargetLibraryInfo *TLI)
Return a location representing a particular argument of a call.
An instruction for storing to memory.
Definition: Instructions.h:292
Provides information about what library functions are available for the current target.
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
LLVM Value Representation.
Definition: Value.h:74
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition: TypeSize.h:168
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Other
Any other memory.
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
Definition: APFixedPoint.h:303
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition: Metadata.h:760
static LocationSize getTombstoneKey()
static bool isEqual(const LocationSize &LHS, const LocationSize &RHS)
static unsigned getHashValue(const LocationSize &Val)
static LocationSize getEmptyKey()
static MemoryLocation getTombstoneKey()
static MemoryLocation getEmptyKey()
static bool isEqual(const MemoryLocation &LHS, const MemoryLocation &RHS)
static unsigned getHashValue(const MemoryLocation &Val)
An information struct used to provide DenseMap with the various necessary components for a given valu...
Definition: DenseMapInfo.h:52