LLVM 24.0.0git
Evaluator.h
Go to the documentation of this file.
1//===- Evaluator.h - LLVM IR evaluator --------------------------*- 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// Function evaluator for LLVM IR.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_TRANSFORMS_UTILS_EVALUATOR_H
14#define LLVM_TRANSFORMS_UTILS_EVALUATOR_H
15
16#include "llvm/ADT/DenseMap.h"
19#include "llvm/IR/BasicBlock.h"
22#include <cassert>
23#include <deque>
24#include <memory>
25
26namespace llvm {
27
28class CallBase;
29class DataLayout;
30class Function;
32
33/// This class evaluates LLVM IR, producing the Constant representing each SSA
34/// instruction. Changes to global variables are stored in a mapping that can
35/// be iterated over after the evaluation is complete. Once an evaluation call
36/// fails, the evaluation object should not be reused.
37class Evaluator {
38 struct MutableAggregate;
39
40 /// The evaluator represents values either as a Constant*, or as a
41 /// MutableAggregate, which allows changing individual aggregate elements
42 /// without creating a new interned Constant.
43 class MutableValue {
45 LLVM_ABI void clear();
46 bool makeMutable();
47
48 public:
49 MutableValue(Constant *C) { Val = C; }
50 MutableValue(const MutableValue &) = delete;
51 MutableValue(MutableValue &&Other) {
52 Val = Other.Val;
53 Other.Val = nullptr;
54 }
55 ~MutableValue() { clear(); }
56
57 Type *getType() const {
58 if (auto *C = dyn_cast_if_present<Constant *>(Val))
59 return C->getType();
60 return cast<MutableAggregate *>(Val)->Ty;
61 }
62
63 Constant *toConstant() const {
64 if (auto *C = dyn_cast_if_present<Constant *>(Val))
65 return C;
66 return cast<MutableAggregate *>(Val)->toConstant();
67 }
68
69 LLVM_ABI Constant *read(Type *Ty, APInt Offset, const DataLayout &DL) const;
70 LLVM_ABI bool write(Constant *V, APInt Offset, const DataLayout &DL);
71 };
72
73 struct MutableAggregate {
74 Type *Ty;
76
77 MutableAggregate(Type *Ty) : Ty(Ty) {}
78 LLVM_ABI Constant *toConstant() const;
79 };
80
81public:
83 const function_ref<TargetLibraryInfo &(Function &)> GetTLI)
84 : DL(DL), GetTLI(GetTLI) {
85 ValueStack.emplace_back();
86 }
87
89 for (auto &Tmp : AllocaTmps)
90 // If there are still users of the alloca, the program is doing something
91 // silly, e.g. storing the address of the alloca somewhere and using it
92 // later. Since this is undefined, we'll just make it be null.
93 if (!Tmp->use_empty())
94 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
95 }
96
97 /// Evaluate a call to function F, returning true if successful, false if we
98 /// can't evaluate it. ActualArgs contains the formal arguments for the
99 /// function.
101 const SmallVectorImpl<Constant *> &ActualArgs);
102
105 for (const auto &Pair : MutatedMemory)
106 Result[Pair.first] = Pair.second.toConstant();
107 return Result;
108 }
109
111 return Invariants;
112 }
113
114private:
115 bool EvaluateBlock(BasicBlock::iterator CurInst, TargetLibraryInfo *TLI,
116 BasicBlock *&NextBB,
117 bool &StrippedPointerCastsForAliasAnalysis);
118
120 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
121 Constant *R = ValueStack.back().lookup(V);
122 assert(R && "Reference to an uncomputed value!");
123 return R;
124 }
125
126 void setVal(Value *V, Constant *C) {
127 ValueStack.back()[V] = C;
128 }
129
130 /// Given call site return callee and list of its formal arguments
131 Function *getCalleeWithFormalArgs(CallBase &CB,
132 SmallVectorImpl<Constant *> &Formals);
133
134 /// Given call site and callee returns list of callee formal argument
135 /// values converting them when necessary
136 bool getFormalParams(CallBase &CB, Function *F,
137 SmallVectorImpl<Constant *> &Formals);
138
139 Constant *ComputeLoadResult(Constant *P, Type *Ty);
140 Constant *ComputeLoadResult(GlobalVariable *GV, Type *Ty,
141 const APInt &Offset);
142
143 /// As we compute SSA register values, we store their contents here. The back
144 /// of the deque contains the current function and the stack contains the
145 /// values in the calling frames.
146 std::deque<DenseMap<Value*, Constant*>> ValueStack;
147
148 /// This is used to detect recursion. In pathological situations we could hit
149 /// exponential behavior, but at least there is nothing unbounded.
151
152 /// For each store we execute, we update this map. Loads check this to get
153 /// the most up-to-date value. If evaluation is successful, this state is
154 /// committed to the process.
155 DenseMap<GlobalVariable *, MutableValue> MutatedMemory;
156
157 /// To 'execute' an alloca, we create a temporary global variable to represent
158 /// its body. This vector is needed so we can delete the temporary globals
159 /// when we are done.
161
162 /// These global variables have been marked invariant by the static
163 /// constructor.
164 SmallPtrSet<GlobalVariable*, 8> Invariants;
165
166 /// These are constants we have checked and know to be simple enough to live
167 /// in a static initializer of a global.
168 SmallPtrSet<Constant*, 8> SimpleConstants;
169
170 const DataLayout &DL;
171 function_ref<TargetLibraryInfo &(Function &)> GetTLI;
172};
173
174} // end namespace llvm
175
176#endif // LLVM_TRANSFORMS_UTILS_EVALUATOR_H
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
#define LLVM_ABI
Definition Compiler.h:211
This file defines the DenseMap class.
#define F(x, y, z)
Definition MD5.cpp:54
#define P(N)
static bool getVal(MDTuple *MD, const char *Key, uint64_t &Val)
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM Basic Block Representation.
Definition BasicBlock.h:62
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
This is an important base class in LLVM.
Definition Constant.h:44
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Evaluator(const DataLayout &DL, const function_ref< TargetLibraryInfo &(Function &)> GetTLI)
Definition Evaluator.h:82
DenseMap< GlobalVariable *, Constant * > getMutatedInitializers() const
Definition Evaluator.h:103
LLVM_ABI bool EvaluateFunction(Function *F, Constant *&RetVal, const SmallVectorImpl< Constant * > &ActualArgs)
Evaluate a call to function F, returning true if successful, false if we can't evaluate it.
const SmallPtrSetImpl< GlobalVariable * > & getInvariants() const
Definition Evaluator.h:110
A discriminated union of two or more pointer types, with the discriminator in the low bits of the poi...
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
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
LLVM Value Representation.
Definition Value.h:75
An efficient, type-erasing, non-owning reference to a callable.
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
@ Other
Any other memory.
Definition ModRef.h:68
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI Error write(DWPWriter &Out, ArrayRef< std::string > Inputs, OnCuIndexOverflow OverflowOptValue, Dwarf64StrOffsetsPromotion StrOffsetsOptValue, raw_pwrite_stream *OS=nullptr)
Definition DWP.cpp:746