LLVM 24.0.0git
MemoryBuiltins.h
Go to the documentation of this file.
1//==- llvm/Analysis/MemoryBuiltins.h - Calls to memory builtins --*- 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 family of functions identifies calls to builtin functions that allocate
10// or free memory.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_ANALYSIS_MEMORYBUILTINS_H
15#define LLVM_ANALYSIS_MEMORYBUILTINS_H
16
17#include "llvm/ADT/APInt.h"
18#include "llvm/ADT/DenseMap.h"
21#include "llvm/IR/IRBuilder.h"
22#include "llvm/IR/InstVisitor.h"
23#include "llvm/IR/ValueHandle.h"
25#include <cstdint>
26#include <optional>
27#include <utility>
28
29namespace llvm {
30
31class AllocaInst;
32class AAResults;
33class Argument;
35class DataLayout;
38class GEPOperator;
39class GlobalAlias;
40class GlobalVariable;
41class Instruction;
42class IntegerType;
43class IntrinsicInst;
44class IntToPtrInst;
45class LLVMContext;
46class LoadInst;
47class PHINode;
48class SelectInst;
49class Type;
50class UndefValue;
51class Value;
52
53/// Tests if a value is a call or invoke to a library function that
54/// allocates or reallocates memory (either malloc, calloc, realloc, or strdup
55/// like).
56LLVM_ABI bool isAllocationFn(const Value *V);
57
58/// Tests if a value is a call or invoke to a library function that
59/// allocates memory (either malloc, calloc, or strdup like).
60LLVM_ABI bool isAllocLikeFn(const Value *V);
61
62/// Tests if a function is a call or invoke to a library function that
63/// reallocates memory (e.g., realloc).
65
66/// If this is a call to a realloc function, return the reallocated operand.
68
69//===----------------------------------------------------------------------===//
70// free Call Utility Functions.
71//
72
73/// Returns true if the function has allockind(free).
74LLVM_ABI bool isFreeLikeFn(const Function *F);
75
76/// If this if a call to a free function, return the freed operand.
78
79/// If this is a call to a free function that returns a value, return the value
80/// that will be returned when it is elided, i.e. when a free(malloc(...)) pair
81/// is eliminated. Returns nullptr on free functions with void return type.
83
84//===----------------------------------------------------------------------===//
85// Properties of allocation functions
86//
87
88/// Return true if this is a call to an allocation function that does not have
89/// side effects that we are required to preserve beyond the effect of
90/// allocating a new object.
91/// Ex: If our allocation routine has a counter for the number of objects
92/// allocated, and the program prints it on exit, can the value change due
93/// to optimization? Answer is highly language dependent.
94/// Note: *Removable* really does mean removable; it does not mean observable.
95/// A language (e.g. C++) can allow removing allocations without allowing
96/// insertion or speculative execution of allocation routines.
98
99/// Gets the alignment argument for an aligned_alloc-like function based on the
100/// allocalign attribute.
101/// Note: the Value returned may not indicate a valid alignment, per
102/// the definition of the allocalign attribute.
104
105/// Return the size of the requested allocation. With a trivial mapper, this is
106/// similar to calling getObjectSize(..., Exact), but without looking through
107/// calls that return their argument. A mapper function can be used to replace
108/// one Value* (operand to the allocation) with another. This is useful when
109/// doing abstract interpretation.
110LLVM_ABI std::optional<APInt> getAllocSize(
111 const CallBase *CB, const TargetLibraryInfo *TLI,
112 function_ref<const Value *(const Value *)> Mapper = [](const Value *V) {
113 return V;
114 });
115
116/// If this is a call to an allocation function that initializes memory to a
117/// fixed value, return said value in the requested type. Otherwise, return
118/// nullptr.
120
121/// If a function is part of an allocation family (e.g.
122/// malloc/realloc/calloc/free), return the identifier for its family
123/// of functions.
124LLVM_ABI std::optional<StringRef> getAllocationFamily(const Value *I);
125
126//===----------------------------------------------------------------------===//
127// Utility functions to compute size of objects.
128//
129
130/// Various options to control the behavior of getObjectSize.
132 /// Controls how we handle conditional statements with unknown conditions.
133 enum class Mode : uint8_t {
134 /// All branches must be known and have the same size, starting from the
135 /// offset, to be merged.
137 /// All branches must be known and have the same underlying size and offset
138 /// to be merged.
140 /// Evaluate all branches of an unknown condition. If all evaluations
141 /// succeed, pick the minimum size.
143 /// Same as Min, except we pick the maximum size of all of the branches.
145 };
146
147 /// How we want to evaluate this object's size.
149 /// Whether to round the result up to the alignment of allocas, byval
150 /// arguments, and global variables.
151 bool RoundToAlign = false;
152 /// If this is true, null pointers in address space 0 will be treated as
153 /// though they can't be evaluated. Otherwise, null is always considered to
154 /// point to a 0 byte region of memory.
155 bool NullIsUnknownSize = false;
156 /// If set, used for more accurate evaluation
157 AAResults *AA = nullptr;
158};
159
160/// Compute the size of the object pointed by Ptr. Returns true and the
161/// object size in Size if successful, and false otherwise. In this context, by
162/// object we mean the region of memory starting at Ptr to the end of the
163/// underlying object pointed to by Ptr.
164///
165/// WARNING: The object size returned is the allocation size. This does not
166/// imply dereferenceability at site of use since the object may be freeed in
167/// between.
168LLVM_ABI bool getObjectSize(const Value *Ptr, uint64_t &Size,
169 const DataLayout &DL, const TargetLibraryInfo *TLI,
170 ObjectSizeOpts Opts = {});
171
172/// Like getObjectSize(), but only returns the size of base objects (like
173/// allocas, global variables and allocator calls) and std::nullopt otherwise.
174/// Requires ExactSizeFromOffset mode.
175LLVM_ABI std::optional<TypeSize> getBaseObjectSize(const Value *Ptr,
176 const DataLayout &DL,
177 const TargetLibraryInfo *TLI,
178 ObjectSizeOpts Opts = {});
179
180/// Try to turn a call to \@llvm.objectsize into an integer value of the given
181/// Type. Returns null on failure. If MustSucceed is true, this function will
182/// not return null, and may return conservative values governed by the second
183/// argument of the call to objectsize.
185 const DataLayout &DL,
186 const TargetLibraryInfo *TLI,
187 bool MustSucceed);
189 IntrinsicInst *ObjectSize, const DataLayout &DL,
190 const TargetLibraryInfo *TLI, AAResults *AA, bool MustSucceed,
191 SmallVectorImpl<Instruction *> *InsertedInstructions = nullptr);
192
193/// SizeOffsetType - A base template class for the object size visitors. Used
194/// here as a self-documenting way to handle the values rather than using a
195/// \p std::pair.
196template <typename T, class C> struct SizeOffsetType {
197public:
200
201 SizeOffsetType() = default;
204
205 bool knownSize() const { return C::known(Size); }
206 bool knownOffset() const { return C::known(Offset); }
207 bool anyKnown() const { return knownSize() || knownOffset(); }
208 bool bothKnown() const { return knownSize() && knownOffset(); }
209
211 return Size == RHS.Size && Offset == RHS.Offset;
212 }
214 return !(*this == RHS);
215 }
216};
217
218/// SizeOffsetAPInt - Used by \p ObjectSizeOffsetVisitor, which works with
219/// \p APInts.
220struct SizeOffsetAPInt : public SizeOffsetType<APInt, SizeOffsetAPInt> {
221 SizeOffsetAPInt() = default;
224
225 static bool known(const APInt &V) { return V.getBitWidth() > 1; }
226};
227
228/// OffsetSpan - Used internally by \p ObjectSizeOffsetVisitor. Represents a
229/// point in memory as a pair of allocated bytes before and after it.
230///
231/// \c Before and \c After fields are signed values. It makes it possible to
232/// represent out-of-bound access, e.g. as a result of a GEP, at the expense of
233/// not being able to represent very large allocation.
235 APInt Before; /// Number of allocated bytes before this point.
236 APInt After; /// Number of allocated bytes after this point.
237
238 OffsetSpan() = default;
240
241 bool knownBefore() const { return known(Before); }
242 bool knownAfter() const { return known(After); }
243 bool anyKnown() const { return knownBefore() || knownAfter(); }
244 bool bothKnown() const { return knownBefore() && knownAfter(); }
245
246 bool operator==(const OffsetSpan &RHS) const {
247 return Before == RHS.Before && After == RHS.After;
248 }
249 bool operator!=(const OffsetSpan &RHS) const { return !(*this == RHS); }
250
251 static bool known(const APInt &V) { return V.getBitWidth() > 1; }
252};
253
254/// Evaluate the size and offset of an object pointed to by a Value*
255/// statically. Fails if size or offset are not known at compile time.
257 : public InstVisitor<ObjectSizeOffsetVisitor, OffsetSpan> {
258 const DataLayout &DL;
259 const TargetLibraryInfo *TLI;
260 ObjectSizeOpts Options;
261 unsigned IntTyBits;
262 APInt Zero;
264 unsigned InstructionsVisited;
265
267
268 static OffsetSpan unknown() { return OffsetSpan(); }
269
270public:
272 const TargetLibraryInfo *TLI,
274 ObjectSizeOpts Options = {});
275
277
278 // These are "private", except they can't actually be made private. Only
279 // compute() should be used by external users.
294
295private:
297 findLoadOffsetRange(LoadInst &LoadFrom, BasicBlock &BB,
300 unsigned &ScannedInstCount);
301 OffsetSpan combineOffsetRange(OffsetSpan LHS, OffsetSpan RHS);
302 OffsetSpan computeImpl(Value *V);
303 OffsetSpan computeValue(Value *V);
304 bool checkedZextOrTrunc(APInt &I);
305};
306
307/// SizeOffsetValue - Used by \p ObjectSizeOffsetEvaluator, which works with
308/// \p Values.
310struct SizeOffsetValue : public SizeOffsetType<Value *, SizeOffsetValue> {
311 SizeOffsetValue() : SizeOffsetType(nullptr, nullptr) {}
314
315 static bool known(Value *V) { return V != nullptr; }
316};
317
318/// SizeOffsetWeakTrackingVH - Used by \p ObjectSizeOffsetEvaluator in a
319/// \p DenseMap.
321 : public SizeOffsetType<WeakTrackingVH, SizeOffsetWeakTrackingVH> {
327
328 static bool known(WeakTrackingVH V) { return V.pointsToAliveValue(); }
329};
330
331/// Evaluate the size and offset of an object pointed to by a Value*.
332/// May create code to compute the result at run-time.
334 : public InstVisitor<ObjectSizeOffsetEvaluator, SizeOffsetValue> {
336 using WeakEvalType = SizeOffsetWeakTrackingVH;
337 using CacheMapTy = DenseMap<const Value *, WeakEvalType>;
338 using PtrSetTy = SmallPtrSet<const Value *, 8>;
339
340 const DataLayout &DL;
341 const TargetLibraryInfo *TLI;
342 LLVMContext &Context;
343 BuilderTy Builder;
344 IntegerType *IntTy;
345 Value *Zero;
346 CacheMapTy CacheMap;
347 PtrSetTy SeenVals;
348 ObjectSizeOpts EvalOpts;
349 SmallPtrSet<Instruction *, 8> InsertedInstructions;
350
351 SizeOffsetValue compute_(Value *V);
352
353public:
355 ObjectSizeOpts EvalOpts = {});
356
358
360
361 // The individual instruction visitors should be treated as private.
372};
373
374} // end namespace llvm
375
376#endif // LLVM_ANALYSIS_MEMORYBUILTINS_H
const TargetLowering & TLI
uint64_t uint64_t
Rewrite undef for PHI
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
#define LLVM_ABI
Definition Compiler.h:211
SmallPtrSet< const BasicBlock *, 8 > VisitedBlocks
This file defines the DenseMap class.
Hexagon Common GEP
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
This file defines the SmallPtrSet class.
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition APInt.h:78
an instruction to allocate memory on the stack
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
LLVM Basic Block Representation.
Definition BasicBlock.h:61
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:169
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
A constant pointer value that points to null.
Definition Constants.h:716
This is an important base class in LLVM.
Definition Constant.h:44
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
This instruction extracts a single (scalar) element from a VectorType value.
This instruction extracts a struct member or array element value from an aggregate value.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
Base class for instruction visitors.
Definition InstVisitor.h:78
This class represents a cast from an integer to a pointer.
Class to represent integer types.
A wrapper class for inspecting calls to intrinsic functions.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
An instruction for reading from memory.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
LLVM_ABI SizeOffsetValue visitExtractValueInst(ExtractValueInst &I)
LLVM_ABI SizeOffsetValue visitExtractElementInst(ExtractElementInst &I)
LLVM_ABI SizeOffsetValue compute(Value *V)
LLVM_ABI SizeOffsetValue visitInstruction(Instruction &I)
LLVM_ABI SizeOffsetValue visitLoadInst(LoadInst &I)
LLVM_ABI SizeOffsetValue visitGEPOperator(GEPOperator &GEP)
LLVM_ABI SizeOffsetValue visitIntToPtrInst(IntToPtrInst &)
LLVM_ABI SizeOffsetValue visitPHINode(PHINode &PHI)
LLVM_ABI SizeOffsetValue visitCallBase(CallBase &CB)
LLVM_ABI ObjectSizeOffsetEvaluator(Module &M, const TargetLibraryInfo *TLI, ObjectSizeOpts EvalOpts={})
LLVM_ABI SizeOffsetValue visitSelectInst(SelectInst &I)
LLVM_ABI SizeOffsetValue visitAllocaInst(AllocaInst &I)
static SizeOffsetValue unknown()
LLVM_ABI OffsetSpan visitSelectInst(SelectInst &I)
LLVM_ABI OffsetSpan visitExtractValueInst(ExtractValueInst &I)
LLVM_ABI OffsetSpan visitConstantPointerNull(ConstantPointerNull &)
LLVM_ABI OffsetSpan visitExtractElementInst(ExtractElementInst &I)
LLVM_ABI OffsetSpan visitGlobalVariable(GlobalVariable &GV)
LLVM_ABI OffsetSpan visitCallBase(CallBase &CB)
LLVM_ABI OffsetSpan visitIntToPtrInst(IntToPtrInst &)
LLVM_ABI OffsetSpan visitAllocaInst(AllocaInst &I)
LLVM_ABI ObjectSizeOffsetVisitor(const DataLayout &DL, const TargetLibraryInfo *TLI, LLVMContext &Context, ObjectSizeOpts Options={})
LLVM_ABI OffsetSpan visitLoadInst(LoadInst &I)
LLVM_ABI OffsetSpan visitPHINode(PHINode &)
LLVM_ABI OffsetSpan visitGlobalAlias(GlobalAlias &GA)
LLVM_ABI OffsetSpan visitInstruction(Instruction &I)
LLVM_ABI SizeOffsetAPInt compute(Value *V)
LLVM_ABI OffsetSpan visitUndefValue(UndefValue &)
LLVM_ABI OffsetSpan visitArgument(Argument &A)
This class represents the LLVM 'select' instruction.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Provides information about what library functions are available for the current target.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
'undef' values are things that do not have specified contents.
Definition Constants.h:1657
LLVM Value Representation.
Definition Value.h:75
Value handle that is nullable, but tries to track the Value.
An efficient, type-erasing, non-owning reference to a callable.
Abstract Attribute helper functions.
Definition Attributor.h:166
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI Value * getAllocAlignment(const CallBase *V)
Gets the alignment argument for an aligned_alloc-like function based on the allocalign attribute.
LLVM_ABI std::optional< StringRef > getAllocationFamily(const Value *I)
If a function is part of an allocation family (e.g.
LLVM_ABI Value * lowerObjectSizeCall(IntrinsicInst *ObjectSize, const DataLayout &DL, const TargetLibraryInfo *TLI, bool MustSucceed)
Try to turn a call to @llvm.objectsize into an integer value of the given Type.
LLVM_ABI Value * getReallocatedOperand(const CallBase *CB)
If this is a call to a realloc function, return the reallocated operand.
LLVM_ABI std::optional< TypeSize > getBaseObjectSize(const Value *Ptr, const DataLayout &DL, const TargetLibraryInfo *TLI, ObjectSizeOpts Opts={})
Like getObjectSize(), but only returns the size of base objects (like allocas, global variables and a...
LLVM_ABI bool getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout &DL, const TargetLibraryInfo *TLI, ObjectSizeOpts Opts={})
Compute the size of the object pointed by Ptr.
LLVM_ABI bool isAllocLikeFn(const Value *V)
Tests if a value is a call or invoke to a library function that allocates memory (either malloc,...
LLVM_ABI Constant * getInitialValueOfAllocation(const Value *V, Type *Ty)
If this is a call to an allocation function that initializes memory to a fixed value,...
LLVM_ABI bool isFreeLikeFn(const Function *F)
Returns true if the function has allockind(free).
LLVM_ABI bool isReallocLikeFn(const Function *F)
Tests if a function is a call or invoke to a library function that reallocates memory (e....
LLVM_ABI bool isAllocationFn(const Value *V)
Tests if a value is a call or invoke to a library function that allocates or reallocates memory (eith...
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
LLVM_ABI std::optional< APInt > getAllocSize(const CallBase *CB, const TargetLibraryInfo *TLI, function_ref< const Value *(const Value *)> Mapper=[](const Value *V) { return V;})
Return the size of the requested allocation.
LLVM_ABI Constant * getElidedFreeResult(const Value *V)
If this is a call to a free function that returns a value, return the value that will be returned whe...
LLVM_ABI Value * getFreedOperand(const CallBase *CB)
If this if a call to a free function, return the freed operand.
LLVM_ABI bool isRemovableAlloc(const CallBase *V)
Return true if this is a call to an allocation function that does not have side effects that we are r...
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:111
Various options to control the behavior of getObjectSize.
bool NullIsUnknownSize
If this is true, null pointers in address space 0 will be treated as though they can't be evaluated.
Mode EvalMode
How we want to evaluate this object's size.
AAResults * AA
If set, used for more accurate evaluation.
bool RoundToAlign
Whether to round the result up to the alignment of allocas, byval arguments, and global variables.
Mode
Controls how we handle conditional statements with unknown conditions.
@ ExactUnderlyingSizeAndOffset
All branches must be known and have the same underlying size and offset to be merged.
@ Max
Same as Min, except we pick the maximum size of all of the branches.
@ Min
Evaluate all branches of an unknown condition.
@ ExactSizeFromOffset
All branches must be known and have the same size, starting from the offset, to be merged.
OffsetSpan - Used internally by ObjectSizeOffsetVisitor.
OffsetSpan()=default
Number of allocated bytes after this point.
bool knownBefore() const
APInt After
Number of allocated bytes before this point.
bool anyKnown() const
bool knownAfter() const
static bool known(const APInt &V)
bool operator!=(const OffsetSpan &RHS) const
bool operator==(const OffsetSpan &RHS) const
OffsetSpan(APInt Before, APInt After)
bool bothKnown() const
SizeOffsetAPInt - Used by ObjectSizeOffsetVisitor, which works with APInts.
static bool known(const APInt &V)
SizeOffsetAPInt(APInt Size, APInt Offset)
bool operator!=(const SizeOffsetType< T, C > &RHS) const
bool operator==(const SizeOffsetType< T, C > &RHS) const
SizeOffsetType()=default
SizeOffsetType(T Size, T Offset)
SizeOffsetValue(Value *Size, Value *Offset)
static bool known(Value *V)
SizeOffsetWeakTrackingVH - Used by ObjectSizeOffsetEvaluator in a DenseMap.
SizeOffsetWeakTrackingVH(const SizeOffsetValue &SOV)
static bool known(WeakTrackingVH V)
SizeOffsetWeakTrackingVH(Value *Size, Value *Offset)