28#include <mlir/Analysis/DataFlow/DenseAnalysis.h>
29#include <mlir/IR/BuiltinOps.h>
30#include <mlir/Pass/AnalysisManager.h>
31#include <mlir/Support/LLVM.h>
33#include <llvm/ADT/DynamicAPInt.h>
34#include <llvm/ADT/MapVector.h>
35#include <llvm/Support/SMTAPI.h>
54 : i(
Interval::Entire(f)), expr(exprRef) {}
57 : i(
Interval::Degenerate(f, singleVal)), expr(exprRef) {}
60 : i(interval), expr(exprRef) {}
62 llvm::SMTExprRef
getExpr()
const {
return expr; }
89 bool isBoolSort(
const llvm::SMTSolverRef &solver)
const {
90 return solver->getBoolSort() == solver->getSort(expr);
128 const llvm::SMTSolverRef &solver, mlir::Operation *op,
const ExpressionValue &lhs,
133 const llvm::SMTSolverRef &solver, mlir::Operation *op,
const ExpressionValue &lhs,
177 const llvm::SMTSolverRef &solver, mlir::Operation *op,
const ExpressionValue &val
182 void print(mlir::raw_ostream &os)
const;
197 llvm::SMTExprRef expr;
206 using AbstractLatticeValue::AbstractLatticeValue;
217 using ValueMap = mlir::DenseMap<mlir::Value, LatticeValue>;
220 using MemberMap = mlir::DenseMap<mlir::Value, mlir::DenseMap<mlir::StringAttr, LatticeValue>>;
226 using AbstractSparseLattice::AbstractSparseLattice;
228 mlir::ChangeResult
join(
const AbstractSparseLattice &other)
override;
230 mlir::ChangeResult
meet(
const AbstractSparseLattice &other)
override;
232 void print(mlir::raw_ostream &os)
const override;
265 using SymbolMap = mlir::DenseMap<SourceRef, llvm::SMTExprRef>;
269 mlir::DataFlowSolver &dataflowSolver, llvm::SMTSolverRef
smt,
const Field &f,
270 bool propInputConstraints
273 smtSolver(std::move(
smt)), field(f), propagateInputConstraints(propInputConstraints) {}
276 mlir::Operation *op, mlir::ArrayRef<const Lattice *> operands,
277 mlir::ArrayRef<Lattice *> results
286 const llvm::DenseMap<SourceRef, llvm::DenseSet<Lattice *>> &
getReadResults()
const {
290 const llvm::DenseMap<SourceRef, ExpressionValue> &
getWriteResults()
const {
return writeResults; }
293 mlir::DataFlowSolver &_dataflowSolver;
294 llvm::SMTSolverRef smtSolver;
295 SymbolMap refSymbols;
296 std::reference_wrapper<const Field> field;
297 bool propagateInputConstraints;
298 mlir::SymbolTableCollection
tables;
301 llvm::DenseMap<SourceRef, llvm::DenseSet<Lattice *>> readResults;
303 llvm::DenseMap<SourceRef, ExpressionValue> writeResults;
305 void setToEntryState(Lattice *lattice)
override {
310 static bool isBooleanType(mlir::Type ty) {
311 if (
auto intTy = llvm::dyn_cast<mlir::IntegerType>(ty)) {
312 return intTy.getWidth() == 1;
317 Interval getDefaultIntervalForType(mlir::Type ty)
const {
318 return isBooleanType(ty) ?
Interval::Boolean(field.get()) : Interval::Entire(field.get());
321 llvm::SMTExprRef createSymbol(mlir::Type ty,
const char *name)
const;
323 llvm::SMTExprRef createSymbol(
const SourceRef &r)
const;
325 llvm::SMTExprRef createSymbol(mlir::Value val)
const;
327 ExpressionValue createUnknownValue(mlir::Value val)
const {
328 return ExpressionValue(createSymbol(val), getDefaultIntervalForType(val.getType()));
331 inline bool isConstOp(mlir::Operation *op)
const {
333 felt::FeltConstantOp, mlir::arith::ConstantIndexOp, mlir::arith::ConstantIntOp>(op);
336 inline bool isBoolConstOp(mlir::Operation *op)
const {
337 if (
auto constIntOp = llvm::dyn_cast<mlir::arith::ConstantIntOp>(op)) {
338 auto valAttr = dyn_cast<mlir::IntegerAttr>(constIntOp.getValue());
339 ensure(valAttr !=
nullptr,
"arith::ConstantIntOp must have an IntegerAttr as its value");
340 return valAttr.getValue().getBitWidth() == 1;
345 llvm::DynamicAPInt getConst(mlir::Operation *op)
const;
347 inline llvm::SMTExprRef createConstBitvectorExpr(
const llvm::DynamicAPInt &v)
const {
348 return createConstBitvectorExpr(
toAPSInt(v));
351 inline llvm::SMTExprRef createConstBitvectorExpr(
const llvm::APSInt &v)
const {
352 return smtSolver->mkBitvector(v, field.get().bitWidth());
355 llvm::SMTExprRef createConstBoolExpr(
bool v)
const {
return smtSolver->mkBoolean(v); }
357 bool isArithmeticOp(mlir::Operation *op)
const {
359 felt::AddFeltOp, felt::SubFeltOp, felt::MulFeltOp, felt::DivFeltOp, felt::UnsignedModFeltOp,
360 felt::SignedModFeltOp, felt::SignedIntDivFeltOp, felt::UnsignedIntDivFeltOp,
361 mlir::arith::XOrIOp, felt::NegFeltOp, felt::InvFeltOp, felt::AndFeltOp, felt::OrFeltOp,
362 felt::XorFeltOp, felt::NotFeltOp, felt::ShlFeltOp, felt::ShrFeltOp, boolean::CmpOp,
363 boolean::AndBoolOp, boolean::OrBoolOp, boolean::XorBoolOp, boolean::NotBoolOp>(op);
367 performBinaryArithmetic(mlir::Operation *op,
const LatticeValue &a,
const LatticeValue &b);
369 ExpressionValue performUnaryArithmetic(mlir::Operation *op,
const LatticeValue &a);
377 void applyInterval(mlir::Operation *originalOp, mlir::Value val, Interval newInterval);
380 mlir::FailureOr<std::pair<llvm::DenseSet<mlir::Value>, Interval>>
381 getGeneralizedDecompInterval(mlir::Operation *baseOp, mlir::Value lhs, mlir::Value rhs);
383 bool isReadOp(mlir::Operation *op)
const {
384 return llvm::isa<component::MemberReadOp, polymorphic::ConstReadOp, array::ReadArrayOp>(op);
387 bool isDefinitionOp(mlir::Operation *op)
const {
389 component::StructDefOp, function::FuncDefOp, component::MemberDefOp, global::GlobalDefOp,
393 bool isReturnOp(mlir::Operation *op)
const {
return llvm::isa<function::ReturnOp>(op); }
398 std::vector<SourceRefIndex>
399 getArrayAccessIndices(mlir::Operation *baseOp, array::ArrayAccessOpInterface arrayAccessOp);
403 mlir::FailureOr<SourceRef>
404 getArrayAccessRef(mlir::Operation *baseOp, array::ArrayAccessOpInterface arrayAccessOp);
408 Interval getRefInterval(
const SourceRef &ref);
413 ExpressionValue getRefValue(
const SourceRef &ref, mlir::Value val);
417 void recordRefWrite(
const SourceRef &writtenRef,
const ExpressionValue &writeVal);
420 SourceRefLatticeValue getSourceRefState(mlir::Value val);
429 std::optional<std::reference_wrapper<const Field>>
field;
435 ensure(
field.has_value(),
"field not set within context");
446template <>
struct std::hash<
llzk::IntervalAnalysisContext> {
448 return llvm::hash_combine(
449 std::hash<const llzk::IntervalDataFlowAnalysis *> {}(c.
intervalDFA),
450 std::hash<const llvm::SMTSolver *> {}(c.
smtSolver.get()),
451 std::hash<const llzk::Field *> {}(&c.
getField()),
461class StructIntervals {
472 static mlir::FailureOr<StructIntervals>
compute(
476 StructIntervals si(mod, s);
478 return mlir::failure();
486 void print(mlir::raw_ostream &os,
bool withConstraints =
false,
bool printCompute =
false)
const;
489 return constrainMemberRanges;
493 return constrainSolverConstraints;
497 return computeMemberRanges;
501 return computeSolverConstraints;
504 friend mlir::raw_ostream &
operator<<(mlir::raw_ostream &os,
const StructIntervals &si) {
512 llvm::SMTSolverRef smtSolver;
514 llvm::MapVector<SourceRef, Interval> constrainMemberRanges, computeMemberRanges;
516 llvm::SetVector<ExpressionValue> constrainSolverConstraints, computeSolverConstraints;
534 if (mlir::failed(computeRes)) {
535 return mlir::failure();
538 return mlir::success();
545 :
public ModuleAnalysis<StructIntervals, IntervalAnalysisContext, StructIntervalAnalysis> {
551 ctx.smtSolver = llvm::CreateZ3Solver();
560 ensure(ctx.hasField(),
"field not set, could not generate analysis context");
562 auto smtSolverRef = ctx.smtSolver;
563 bool prop = ctx.propagateInputConstraints;
566 std::move(smtSolverRef), ctx.getField(),
572 ensure(ctx.field.has_value(),
"field not set, could not generate analysis context");
584template <>
struct DenseMapInfo<
llzk::ExpressionValue> {
587 static const auto *emptyPtr =
reinterpret_cast<SMTExprRef
>(1);
591 static const auto *tombstonePtr =
reinterpret_cast<SMTExprRef
>(2);
Convenience classes for a frequent pattern of dataflow analysis used in LLZK, where an analysis is ru...
This file implements sparse data-flow analysis using the data-flow analysis framework.
Tracks a solver expression and an interval range for that expression.
friend ExpressionValue boolAnd(const llvm::SMTSolverRef &solver, const ExpressionValue &lhs, const ExpressionValue &rhs)
ExpressionValue(llvm::SMTExprRef exprRef, const Interval &interval)
friend ExpressionValue sintDiv(const llvm::SMTSolverRef &solver, mlir::Operation *op, const ExpressionValue &lhs, const ExpressionValue &rhs)
ExpressionValue withExpression(const llvm::SMTExprRef &newExpr) const
Return the current expression with a new SMT expression.
friend ExpressionValue fallbackUnaryOp(const llvm::SMTSolverRef &solver, mlir::Operation *op, const ExpressionValue &val)
friend ExpressionValue bitOr(const llvm::SMTSolverRef &solver, const ExpressionValue &lhs, const ExpressionValue &rhs)
friend ExpressionValue notOp(const llvm::SMTSolverRef &solver, const ExpressionValue &val)
friend ExpressionValue shiftRight(const llvm::SMTSolverRef &solver, const ExpressionValue &lhs, const ExpressionValue &rhs)
friend ExpressionValue intersection(const llvm::SMTSolverRef &solver, const ExpressionValue &lhs, const ExpressionValue &rhs)
Compute the intersection of the lhs and rhs intervals, and create a solver expression that constrains...
friend ExpressionValue uintDiv(const llvm::SMTSolverRef &solver, mlir::Operation *op, const ExpressionValue &lhs, const ExpressionValue &rhs)
const Interval & getInterval() const
friend ExpressionValue mul(const llvm::SMTSolverRef &solver, const ExpressionValue &lhs, const ExpressionValue &rhs)
friend ExpressionValue div(const llvm::SMTSolverRef &solver, mlir::Operation *op, const ExpressionValue &lhs, const ExpressionValue &rhs)
ExpressionValue(const Field &f, llvm::SMTExprRef exprRef)
ExpressionValue(const Field &f)
friend ExpressionValue sub(const llvm::SMTSolverRef &solver, const ExpressionValue &lhs, const ExpressionValue &rhs)
ExpressionValue withInterval(const Interval &newInterval) const
Return the current expression with a new interval.
friend ExpressionValue boolXor(const llvm::SMTSolverRef &solver, const ExpressionValue &lhs, const ExpressionValue &rhs)
void print(mlir::raw_ostream &os) const
bool operator==(const ExpressionValue &rhs) const
friend ExpressionValue shiftLeft(const llvm::SMTSolverRef &solver, const ExpressionValue &lhs, const ExpressionValue &rhs)
friend ExpressionValue mod(const llvm::SMTSolverRef &solver, const ExpressionValue &lhs, const ExpressionValue &rhs)
friend ExpressionValue bitXor(const llvm::SMTSolverRef &solver, const ExpressionValue &lhs, const ExpressionValue &rhs)
friend ExpressionValue bitAnd(const llvm::SMTSolverRef &solver, const ExpressionValue &lhs, const ExpressionValue &rhs)
llvm::SMTExprRef getExpr() const
bool isBoolSort(const llvm::SMTSolverRef &solver) const
friend ExpressionValue cmp(const llvm::SMTSolverRef &solver, boolean::CmpOp op, const ExpressionValue &lhs, const ExpressionValue &rhs)
friend ExpressionValue join(const llvm::SMTSolverRef &solver, const ExpressionValue &lhs, const ExpressionValue &rhs)
Compute the union of the lhs and rhs intervals, and create a solver expression that constrains both s...
ExpressionValue(const Field &f, llvm::SMTExprRef exprRef, const llvm::DynamicAPInt &singleVal)
friend ExpressionValue boolOr(const llvm::SMTSolverRef &solver, const ExpressionValue &lhs, const ExpressionValue &rhs)
friend ExpressionValue boolNot(const llvm::SMTSolverRef &solver, const ExpressionValue &val)
friend mlir::raw_ostream & operator<<(mlir::raw_ostream &os, const ExpressionValue &e)
const Field & getField() const
ExpressionValue & join(const ExpressionValue &)
Fold two expressions together when overapproximating array elements.
friend ExpressionValue neg(const llvm::SMTSolverRef &solver, const ExpressionValue &val)
friend ExpressionValue add(const llvm::SMTSolverRef &solver, const ExpressionValue &lhs, const ExpressionValue &rhs)
Information about the prime finite field used for the interval analysis.
static const Field & getField(llvm::StringRef fieldName, EmitErrorFn errFn)
Get a Field from a given field name string.
friend mlir::raw_ostream & operator<<(mlir::raw_ostream &os, const IntervalAnalysisLattice &l)
const LatticeValue & getValue() const
llvm::SetVector< ExpressionValue > ConstraintSet
mlir::ChangeResult setValue(const LatticeValue &val)
IntervalAnalysisLatticeValue LatticeValue
mlir::DenseMap< mlir::Value, LatticeValue > ValueMap
mlir::ChangeResult meet(const AbstractSparseLattice &other) override
const ConstraintSet & getConstraints() const
mlir::DenseMap< mlir::Value, mlir::DenseMap< mlir::StringAttr, LatticeValue > > MemberMap
void print(mlir::raw_ostream &os) const override
mlir::ChangeResult join(const AbstractSparseLattice &other) override
mlir::ChangeResult setInterval(llvm::SMTExprRef expr, const Interval &i)
mlir::DenseMap< llvm::SMTExprRef, Interval > ExpressionIntervals
mlir::ChangeResult addSolverConstraint(const ExpressionValue &e)
mlir::FailureOr< Interval > findInterval(llvm::SMTExprRef expr) const
mlir::LogicalResult visitOperation(mlir::Operation *op, mlir::ArrayRef< const Lattice * > operands, mlir::ArrayRef< Lattice * > results) override
Visit an operation with the lattices of its operands.
llvm::SMTExprRef getOrCreateSymbol(const SourceRef &r)
Either return the existing SMT expression that corresponds to the SourceRef, or create one.
const llvm::DenseMap< SourceRef, ExpressionValue > & getWriteResults() const
const llvm::DenseMap< SourceRef, llvm::DenseSet< Lattice * > > & getReadResults() const
IntervalDataFlowAnalysis(mlir::DataFlowSolver &dataflowSolver, llvm::SMTSolverRef smt, const Field &f, bool propInputConstraints)
Intervals over a finite field.
static Interval Boolean(const Field &f)
mlir::DataFlowSolver solver
ModuleAnalysis(mlir::Operation *op, const mlir::DataFlowConfig &config=mlir::DataFlowConfig())
ModuleIntervalAnalysis(mlir::Operation *op)
~ModuleIntervalAnalysis() override=default
void setPropagateInputConstraints(bool prop)
void initializeSolver() override
Initialize the shared dataflow solver with any common analyses required by the contained struct analy...
const IntervalAnalysisContext & getContext() const override
Return the current Context object.
void setField(const Field &f)
The dataflow analysis that computes the set of references that LLZK operations use and produce.
A reference to a "source", which is the base value from which other SSA values are derived.
StructAnalysis(mlir::Operation *op)
Assert that this analysis is being run on a StructDefOp and initializes the analysis with the current...
component::StructDefOp getStruct() const
void setResult(const IntervalAnalysisContext &ctx, StructIntervals &&r)
mlir::ModuleOp getModule() const
~StructIntervalAnalysis() override=default
StructAnalysis(mlir::Operation *op)
Assert that this analysis is being run on a StructDefOp and initializes the analysis with the current...
mlir::LogicalResult runAnalysis(mlir::DataFlowSolver &solver, mlir::AnalysisManager &, const IntervalAnalysisContext &ctx) override
Perform the analysis and construct the Result output.
const llvm::MapVector< SourceRef, Interval > & getConstrainIntervals() const
const llvm::SetVector< ExpressionValue > getConstrainSolverConstraints() const
const llvm::SetVector< ExpressionValue > getComputeSolverConstraints() const
const llvm::MapVector< SourceRef, Interval > & getComputeIntervals() const
void print(mlir::raw_ostream &os, bool withConstraints=false, bool printCompute=false) const
static mlir::FailureOr< StructIntervals > compute(mlir::ModuleOp mod, component::StructDefOp s, mlir::DataFlowSolver &solver, const IntervalAnalysisContext &ctx)
Compute the struct intervals.
friend mlir::raw_ostream & operator<<(mlir::raw_ostream &os, const StructIntervals &si)
mlir::LogicalResult computeIntervals(mlir::DataFlowSolver &solver, const IntervalAnalysisContext &ctx)
mlir::SymbolTableCollection tables
LLZK: Added for use of symbol helper caching.
A sparse forward data-flow analysis for propagating SSA value lattices across the IR by implementing ...
SparseForwardDataFlowAnalysis(mlir::DataFlowSolver &s)
mlir::dataflow::AbstractSparseLattice AbstractSparseLattice
ExpressionValue mod(const llvm::SMTSolverRef &solver, const ExpressionValue &lhs, const ExpressionValue &rhs)
void ensure(bool condition, const llvm::Twine &errMsg)
APSInt toAPSInt(const DynamicAPInt &i)
static unsigned getHashValue(const llzk::ExpressionValue &e)
static SMTExprRef getTombstoneExpr()
static bool isEqual(const llzk::ExpressionValue &lhs, const llzk::ExpressionValue &rhs)
static llzk::ExpressionValue getTombstoneKey()
static llzk::ExpressionValue getEmptyKey()
static SMTExprRef getEmptyExpr()
unsigned operator()(const ExpressionValue &e) const
Parameters and shared objects to pass to child analyses.
bool doInputConstraintPropagation() const
const Field & getField() const
friend bool operator==(const IntervalAnalysisContext &a, const IntervalAnalysisContext &b)=default
std::optional< std::reference_wrapper< const Field > > field
IntervalDataFlowAnalysis * intervalDFA
bool propagateInputConstraints
llvm::SMTSolverRef smtSolver
llvm::SMTExprRef getSymbol(const SourceRef &r) const
size_t operator()(const llzk::IntervalAnalysisContext &c) const