LLVM 24.0.0git
ExecutorBase.cpp
Go to the documentation of this file.
1//===- ExecutorBase.cpp - Non-visitor methods of InstExecutor -------------===//
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 implements non-visitor methods of InstExecutor for code reuse.
10//
11//===----------------------------------------------------------------------===//
12
13#include "ExecutorBase.h"
14#include "llvm/ADT/STLExtras.h"
15#include "llvm/ADT/StringRef.h"
16
17#include <cstring>
18
19namespace llvm::ubi {
22 const TargetLibraryInfoImpl &TLIImpl)
24 RetVal(RetVal), TLI(TLIImpl, &F) {
25 assert((Args.size() == F.arg_size() ||
26 (F.isVarArg() && Args.size() >= F.arg_size())) &&
27 "Expected enough arguments to call the function.");
28 BB = &Func.getEntryBlock();
29 PC = BB->begin();
30 for (Argument &Arg : F.args())
31 ValueMap[&Arg] = Args[Arg.getArgNo()];
32}
33
37
41
42void ExecutorBase::reportImmediateUBString(StringRef Msg) {
43 // Check if we have already reported an immediate UB.
44 if (hasProgramExited())
45 return;
49}
50
51void ExecutorBase::reportErrorString(StringRef Msg) {
52 // Check if we have already reported an error message.
53 if (hasProgramExited())
54 return;
58}
59
60std::pair<MemoryObject *, uint64_t>
62 Align Alignment, bool IsStore) {
63 auto *MO = Ctx.checkProvenance(Ptr, [](const Provenance &) {
64 // TODO: check provenance
65 // TODO: check inrange(S, E)
66 return true;
67 });
68 if (!MO) {
70 << "Invalid memory access via a pointer with nullary provenance.";
71 return {};
72 }
73 const APInt &Address = Ptr.address();
74 if (MO->isInaccessible()) {
75 reportImmediateUB() << "Try to access an inaccessible memory object: "
76 << Ptr << ".";
77 return {};
78 }
79 // Loading from a stack object outside its lifetime is not undefined
80 // behavior and returns a poison value instead. Storing to it is still
81 // undefined behavior.
82 if (IsStore ? MO->getState() != MemoryObjectState::Alive
83 : MO->getState() == MemoryObjectState::Freed) {
84 SmallString<32> AddrStr;
85 Address.toStringUnsigned(AddrStr, 16);
86 reportImmediateUB() << "Try to access a dead memory object at address 0x"
87 << AddrStr << ".";
88 return {};
89 }
90
91 if (IsStore && MO->isConstant()) {
92 reportImmediateUB() << "Try to write to a constant memory object: " << Ptr
93 << ".";
94 return {};
95 }
96
97 if (Address.countr_zero() < Log2(Alignment)) {
98 SmallString<32> AddrStr;
99 Address.toStringUnsigned(AddrStr, 16);
100 reportImmediateUB() << "Misaligned memory access. Address: 0x" << AddrStr
101 << ", Required alignment: " << Alignment.value() << ".";
102 return {};
103 }
104
105 if (AccessSize > MO->getSize() || Address.ult(MO->getAddress())) {
106 SmallString<32> AddrStr;
107 Address.toStringUnsigned(AddrStr, 16);
108 reportImmediateUB() << "Memory access is out of bounds. Accessed size: "
109 << AccessSize << ", Address: 0x" << AddrStr
110 << ", Object base: 0x"
111 << Twine::utohexstr(MO->getAddress())
112 << ", Object size: " << MO->getSize() << ".";
113 return {};
114 }
115
116 APInt Offset = Address - MO->getAddress();
117
118 if (Offset.ugt(MO->getSize() - AccessSize)) {
119 SmallString<32> AddrStr;
120 Address.toStringUnsigned(AddrStr, 16);
121 reportImmediateUB() << "Memory access is out of bounds. Accessed size: "
122 << AccessSize << ", Address: 0x" << AddrStr
123 << ", Object base: 0x"
124 << Twine::utohexstr(MO->getAddress())
125 << ", Object size: " << MO->getSize() << ".";
126 return {};
127 }
128
129 return {MO, Offset.getZExtValue()};
130}
131
132AnyValue ExecutorBase::load(const AnyValue &Ptr, Align Alignment, Type *ValTy,
133 bool NoUndef) {
134 if (Ptr.isPoison()) {
135 reportImmediateUB() << "Invalid memory access with a poison pointer.";
136 return AnyValue::getPoisonValue(Ctx, ValTy);
137 }
138 auto &PtrVal = Ptr.asPointer();
139 if (auto [MO, Offset] = verifyMemAccess(
140 PtrVal, Ctx.getEffectiveTypeStoreSize(ValTy), Alignment,
141 /*IsStore=*/false);
142 MO) {
143 bool ContainsUndefinedBits = false;
144 AnyValue Res = Ctx.load(*MO, Offset, ValTy,
145 NoUndef ? &ContainsUndefinedBits : nullptr);
146 if (NoUndef && ContainsUndefinedBits)
147 reportImmediateUB() << "The value loaded contains undefined bits.";
148 return Res;
149 }
150 return AnyValue::getPoisonValue(Ctx, ValTy);
151}
152
153void ExecutorBase::store(const AnyValue &Ptr, Align Alignment,
154 const AnyValue &Val, Type *ValTy) {
155 if (Ptr.isPoison()) {
156 reportImmediateUB() << "Invalid memory access with a poison pointer.";
157 return;
158 }
159 auto &PtrVal = Ptr.asPointer();
160 if (auto [MO, Offset] = verifyMemAccess(
161 PtrVal, Ctx.getEffectiveTypeStoreSize(ValTy), Alignment,
162 /*IsStore=*/true);
163 MO)
164 Ctx.store(*MO, Offset, Val, ValTy);
165}
166
168 const AnyValue &Length, Intrinsic::ID IID,
169 bool IsLibCall) {
170 assert((IID == Intrinsic::memcpy || IID == Intrinsic::memcpy_inline ||
171 IID == Intrinsic::memmove) &&
172 "Unexpected memory transfer intrinsic");
173 const bool IsMemMove = IID == Intrinsic::memmove;
174 const StringRef Name = IsMemMove ? "memmove" : "memcpy";
175
176 if (Length.isPoison()) {
177 reportImmediateUB() << Name << " called with poison length.";
178 return;
179 }
180
181 const std::optional<uint64_t> LenOpt = Length.asInteger().tryZExtValue();
182 if (!LenOpt) {
183 reportImmediateUB() << Name << " called with length overflows uint64_t.";
184 return;
185 }
186 const uint64_t Len = *LenOpt;
187 if (Len == 0)
188 return;
189
190 if (Dest.isPoison()) {
191 reportImmediateUB() << Name << " called with poison destination pointer.";
192 return;
193 }
194
195 if (Src.isPoison()) {
196 reportImmediateUB() << Name << " called with poison source pointer.";
197 return;
198 }
199
200 const Pointer &DstPtr = Dest.asPointer();
201 const Pointer &SrcPtr = Src.asPointer();
202
203 // Alignment attributes have already been handled at the call site.
204 auto [SrcMO, SrcOffset] =
205 verifyMemAccess(SrcPtr, Len, Align(1), /*IsStore=*/false);
206 if (!SrcMO)
207 return;
208
209 auto [DstMO, DstOffset] =
210 verifyMemAccess(DstPtr, Len, Align(1), /*IsStore=*/true);
211 if (!DstMO)
212 return;
213
214 if (!IsMemMove && SrcMO == DstMO) {
215 const uint64_t SrcEnd = SrcOffset + Len;
216 const uint64_t DstEnd = DstOffset + Len;
217 // Unlike the LLVM intrinsic, the C memcpy function also considers equal
218 // source and destination ranges to overlap.
219 if (SrcOffset < DstEnd && DstOffset < SrcEnd &&
220 (IsLibCall || SrcOffset != DstOffset)) {
221 reportImmediateUB() << "memcpy with overlapping source and destination.";
222 return;
223 }
224 }
225
226 MutableArrayRef<Byte> DstBytes = DstMO->getBytes().slice(DstOffset, Len);
227 ArrayRef<Byte> SrcBytes = SrcMO->getBytes().slice(SrcOffset, Len);
228 std::memmove(DstBytes.data(), SrcBytes.data(), Len * sizeof(Byte));
229}
230
231void ExecutorBase::executeMemSet(const AnyValue &Dest, const AnyValue &Val,
232 const AnyValue &Length) {
233 if (Length.isPoison()) {
234 reportImmediateUB() << "memset called with poison length.";
235 return;
236 }
237
238 const std::optional<uint64_t> LenOpt = Length.asInteger().tryZExtValue();
239 if (!LenOpt) {
240 reportImmediateUB() << "memset called with length overflows uint64_t.";
241 return;
242 }
243 const uint64_t Len = *LenOpt;
244 if (Len == 0)
245 return;
246
247 if (Dest.isPoison()) {
248 reportImmediateUB() << "memset called with poison destination pointer.";
249 return;
250 }
251
252 const Pointer &DstPtr = Dest.asPointer();
253
254 // Alignment attributes have already been handled at the call site.
255 auto [DstMO, DstOffset] =
256 verifyMemAccess(DstPtr, Len, Align(1), /*IsStore=*/true);
257 if (!DstMO)
258 return;
259
260 Byte FillByte = Val.isPoison()
261 ? Byte::poison()
263 fill(DstMO->getBytes().slice(DstOffset, Len), FillByte);
264}
265
267 uint64_t ExitCode) {
268 ExitInfo.emplace(Kind, ExitCode);
269 Handler.onProgramExit(*ExitInfo);
270}
271
275
276bool ExecutorBase::hasProgramExited() const { return ExitInfo.has_value(); }
277
278std::optional<ProgramExitInfo> ExecutorBase::getExitInfo() const {
279 return ExitInfo;
280}
281
282unsigned ExecutorBase::getIntSize() const {
283 return CurrentFrame->TLI.getIntSize();
284}
285
287 errs() << "Stacktrace:\n";
288 const Frame *TheFrame = CurrentFrame;
289 unsigned Index = 0;
290 const AsmParserContext *ParserContext = Ctx.getParserContext();
291 StringRef ModuleFileName = Ctx.getModule().getModuleIdentifier();
292 while (TheFrame != nullptr) {
293 if (TheFrame->BB) {
294 Instruction &Inst = *TheFrame->PC;
295 errs() << "#" << Index++ << " " << Inst << " at ";
296 Inst.getFunction()->printAsOperand(errs(), /*PrintType=*/false);
297 if (ParserContext) {
298 if (auto Loc = ParserContext->getInstructionOrArgumentLocation(&Inst))
299 errs() << ' ' << ModuleFileName << ':' << Loc->Start.Line + 1;
300 }
301 errs() << "\n";
302 }
303 TheFrame = TheFrame->LastFrame;
304 }
305}
306} // namespace llvm::ubi
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
#define F(x, y, z)
Definition MD5.cpp:54
const char * Msg
This file contains some templates that are useful if you are working with the STL at all.
Class for arbitrary precision integers.
Definition APInt.h:78
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T * data() const
Definition ArrayRef.h:138
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Definition ArrayRef.h:185
Registry of file location information for LLVM IR constructs.
LLVM_ABI std::optional< FileLocRange > getInstructionOrArgumentLocation(const Value *) const
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
MutableArrayRef< T > slice(size_t N, size_t M) const
Chop off the first N elements of the array, and keep M elements in the array.
Definition ArrayRef.h:372
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:28
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Implementation of the target library information.
static Twine utohexstr(uint64_t Val)
Definition Twine.h:385
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
static LLVM_ABI AnyValue getPoisonValue(Context &Ctx, Type *Ty)
Definition Value.cpp:270
const Pointer & asPointer() const
Definition Value.h:412
const APInt & asInteger() const
Definition Value.h:402
bool isPoison() const
Definition Value.h:374
virtual void onError(StringRef Msg)
Definition Context.h:173
virtual void onImmediateUB(StringRef Msg)
Definition Context.h:175
EventHandler & Handler
unsigned getIntSize() const
DiagnosticReporter reportError()
std::pair< MemoryObject *, uint64_t > verifyMemAccess(const Pointer &Ptr, uint64_t AccessSize, Align Alignment, bool IsStore)
Check if the upcoming memory access is valid.
friend class DiagnosticReporter
void executeMemSet(const AnyValue &Dest, const AnyValue &Val, const AnyValue &Length)
Fill Length bytes at Dest with Val.
std::optional< ProgramExitInfo > ExitInfo
std::optional< ProgramExitInfo > getExitInfo() const
void requestProgramExit(ProgramExitInfo::ProgramExitKind Kind, uint64_t ExitCode=0)
DiagnosticReporter reportImmediateUB()
void store(const AnyValue &Ptr, Align Alignment, const AnyValue &Val, Type *ValTy)
void executeMemTransfer(const AnyValue &Dest, const AnyValue &Src, const AnyValue &Length, Intrinsic::ID IID, bool IsLibCall)
Copy Length bytes from Src to Dest according to the intrinsic IID.
AnyValue load(const AnyValue &Ptr, Align Alignment, Type *ValTy, bool NoUndef)
const APInt & address() const
Definition Value.h:247
Components of a pointer excluding address.
Definition Value.h:188
@ Offset
Definition DWP.cpp:577
@ Length
Definition DWP.cpp:577
void fill(R &&Range, T &&Value)
Provide wrappers to std::fill which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1775
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:202
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Representation of a byte in memory.
Definition Value.h:43
static Byte poison()
Definition Value.h:50
static Byte concrete(uint8_t Val)
Definition Value.h:52
Context for a function call.
Frame(Function &F, CallBase *CallSite, Frame *LastFrame, ArrayRef< AnyValue > Args, AnyValue &RetVal, const TargetLibraryInfoImpl &TLIImpl)
BasicBlock::iterator PC
ArrayRef< AnyValue > Args
BasicBlock * BB
CallBase * CallSite
TargetLibraryInfo TLI
Function & Func
AnyValue & RetVal
DenseMap< Value *, AnyValue > ValueMap