28#include <mlir/IR/BuiltinOps.h>
29#include <mlir/Pass/AnalysisManager.h>
30#include <mlir/Support/LLVM.h>
32#include <llvm/ADT/DynamicAPInt.h>
33#include <llvm/ADT/MapVector.h>
34#include <llvm/Support/SMTAPI.h>
51 : i(
Interval::Entire(f)), expr(exprRef) {}
54 : i(
Interval::Degenerate(f, singleVal)), expr(exprRef) {}
57 : i(interval), expr(exprRef) {}
59 llvm::SMTExprRef
getExpr()
const {
return expr; }
87 return solver->getBoolSort() == solver->getSort(expr);
157 llvm::SMTSolverRef solver, mlir::Operation *op,
const ExpressionValue &lhs,
172 void print(mlir::raw_ostream &os)
const;
187 llvm::SMTExprRef expr;
195 using AbstractLatticeValue::AbstractLatticeValue;
208 using ValueMap = mlir::DenseMap<mlir::Value, LatticeValue>;
211 using FieldMap = mlir::DenseMap<mlir::Value, mlir::DenseMap<mlir::StringAttr, LatticeValue>>;
217 using AbstractDenseLattice::AbstractDenseLattice;
219 mlir::ChangeResult
join(
const AbstractDenseLattice &other)
override;
221 mlir::ChangeResult
meet(
const AbstractDenseLattice & )
override {
222 llvm::report_fatal_error(
"IntervalDataFlowAnalysis::meet : unsupported");
223 return mlir::ChangeResult::NoChange;
226 void print(mlir::raw_ostream &os)
const override;
228 mlir::FailureOr<LatticeValue>
getValue(mlir::Value v)
const;
229 mlir::FailureOr<LatticeValue>
getValue(mlir::Value v, mlir::StringAttr f)
const;
244 mlir::FailureOr<Interval>
findInterval(llvm::SMTExprRef expr)
const;
247 size_t size()
const {
return valMap.size(); }
251 ValueMap::iterator
begin() {
return valMap.begin(); }
252 ValueMap::iterator
end() {
return valMap.end(); }
253 ValueMap::const_iterator
begin()
const {
return valMap.begin(); }
254 ValueMap::const_iterator
end()
const {
return valMap.end(); }
272 using SymbolMap = mlir::DenseMap<SourceRef, llvm::SMTExprRef>;
276 mlir::DataFlowSolver &dataflowSolver, llvm::SMTSolverRef smt,
const Field &f,
277 bool propInputConstraints
279 : Base::DenseForwardDataFlowAnalysis(dataflowSolver), _dataflowSolver(dataflowSolver),
280 smtSolver(smt), field(f), propagateInputConstraints(propInputConstraints) {}
288 visitOperation(mlir::Operation *op,
const Lattice &before, Lattice *after)
override;
297 mlir::DataFlowSolver &_dataflowSolver;
298 llvm::SMTSolverRef smtSolver;
299 SymbolMap refSymbols;
300 std::reference_wrapper<const Field> field;
301 bool propagateInputConstraints;
302 mlir::SymbolTableCollection
tables;
304 void setToEntryState(Lattice *lattice)
override {
308 llvm::SMTExprRef createFeltSymbol(
const SourceRef &r)
const;
310 llvm::SMTExprRef createFeltSymbol(mlir::Value val)
const;
312 llvm::SMTExprRef createFeltSymbol(
const char *
name)
const;
314 bool isConstOp(mlir::Operation *op)
const {
316 felt::FeltConstantOp, mlir::arith::ConstantIndexOp, mlir::arith::ConstantIntOp>(op);
319 llvm::DynamicAPInt getConst(mlir::Operation *op)
const;
321 inline llvm::SMTExprRef createConstBitvectorExpr(
const llvm::DynamicAPInt &v)
const {
322 return createConstBitvectorExpr(
toAPSInt(v));
325 inline llvm::SMTExprRef createConstBitvectorExpr(
const llvm::APSInt &v)
const {
326 return smtSolver->mkBitvector(v, field.get().bitWidth());
329 llvm::SMTExprRef createConstBoolExpr(
bool v)
const {
330 return smtSolver->mkBitvector(mlir::APSInt((
int)v), field.get().bitWidth());
333 bool isArithmeticOp(mlir::Operation *op)
const {
335 felt::AddFeltOp, felt::SubFeltOp, felt::MulFeltOp, felt::DivFeltOp, felt::ModFeltOp,
336 felt::NegFeltOp, felt::InvFeltOp, felt::AndFeltOp, felt::OrFeltOp, felt::XorFeltOp,
337 felt::NotFeltOp, felt::ShlFeltOp, felt::ShrFeltOp, boolean::CmpOp, boolean::AndBoolOp,
338 boolean::OrBoolOp, boolean::XorBoolOp, boolean::NotBoolOp>(op);
342 performBinaryArithmetic(mlir::Operation *op,
const LatticeValue &a,
const LatticeValue &b);
344 ExpressionValue performUnaryArithmetic(mlir::Operation *op,
const LatticeValue &a);
352 mlir::ChangeResult applyInterval(
353 mlir::Operation *originalOp, Lattice *originalLattice, Lattice *after, mlir::Value val,
358 mlir::FailureOr<std::pair<llvm::DenseSet<mlir::Value>, Interval>>
359 getGeneralizedDecompInterval(mlir::Operation *baseOp, mlir::Value lhs, mlir::Value rhs);
361 bool isBoolOp(mlir::Operation *op)
const {
362 return llvm::isa<boolean::AndBoolOp, boolean::OrBoolOp, boolean::XorBoolOp, boolean::NotBoolOp>(
367 bool isConversionOp(mlir::Operation *op)
const {
368 return llvm::isa<cast::IntToFeltOp, cast::FeltToIndexOp>(op);
371 bool isApplyMapOp(mlir::Operation *op)
const {
return llvm::isa<polymorphic::ApplyMapOp>(op); }
373 bool isAssertOp(mlir::Operation *op)
const {
return llvm::isa<boolean::AssertOp>(op); }
375 bool isReadOp(mlir::Operation *op)
const {
376 return llvm::isa<component::FieldReadOp, polymorphic::ConstReadOp, array::ReadArrayOp>(op);
379 bool isWriteOp(mlir::Operation *op)
const {
380 return llvm::isa<component::FieldWriteOp, array::WriteArrayOp, array::InsertArrayOp>(op);
383 bool isArrayLengthOp(mlir::Operation *op)
const {
return llvm::isa<array::ArrayLengthOp>(op); }
385 bool isEmitOp(mlir::Operation *op)
const {
386 return llvm::isa<constrain::EmitEqualityOp, constrain::EmitContainmentOp>(op);
389 bool isCreateOp(mlir::Operation *op)
const {
390 return llvm::isa<component::CreateStructOp, array::CreateArrayOp>(op);
393 bool isExtractArrayOp(mlir::Operation *op)
const {
return llvm::isa<array::ExtractArrayOp>(op); }
395 bool isDefinitionOp(mlir::Operation *op)
const {
397 component::StructDefOp, function::FuncDefOp, component::FieldDefOp, global::GlobalDefOp,
401 bool isCallOp(mlir::Operation *op)
const {
return llvm::isa<function::CallOp>(op); }
403 bool isReturnOp(mlir::Operation *op)
const {
return llvm::isa<function::ReturnOp>(op); }
407 const SourceRefLattice *getSourceRefLattice(mlir::Operation *baseOp, mlir::Value val);
416 std::optional<std::reference_wrapper<const Field>>
field;
422 ensure(
field.has_value(),
"field not set within context");
433template <>
struct std::hash<
llzk::IntervalAnalysisContext> {
435 return llvm::hash_combine(
436 std::hash<const llzk::IntervalDataFlowAnalysis *> {}(c.
intervalDFA),
437 std::hash<const llvm::SMTSolver *> {}(c.
smtSolver.get()),
438 std::hash<const llzk::Field *> {}(&c.
getField()),
446class StructIntervals {
457 static mlir::FailureOr<StructIntervals>
compute(
461 StructIntervals si(mod, s);
463 return mlir::failure();
471 void print(mlir::raw_ostream &os,
bool withConstraints =
false,
bool printCompute =
false)
const;
474 return constrainFieldRanges;
478 return constrainSolverConstraints;
482 return computeFieldRanges;
486 return computeSolverConstraints;
489 friend mlir::raw_ostream &
operator<<(mlir::raw_ostream &os,
const StructIntervals &si) {
497 llvm::SMTSolverRef smtSolver;
499 llvm::MapVector<SourceRef, Interval> constrainFieldRanges, computeFieldRanges;
501 llvm::SetVector<ExpressionValue> constrainSolverConstraints, computeSolverConstraints;
519 if (mlir::failed(computeRes)) {
520 return mlir::failure();
523 return mlir::success();
530 :
public ModuleAnalysis<StructIntervals, IntervalAnalysisContext, StructIntervalAnalysis> {
534 ctx.smtSolver = llvm::CreateZ3Solver();
543 ensure(ctx.hasField(),
"field not set, could not generate analysis context");
545 auto smtSolverRef = ctx.smtSolver;
546 bool prop = ctx.propagateInputConstraints;
549 std::move(smtSolverRef), ctx.getField(), std::move(prop)
554 ensure(ctx.field.has_value(),
"field not set, could not generate analysis context");
566template <>
struct DenseMapInfo<
llzk::ExpressionValue> {
569 static auto emptyPtr =
reinterpret_cast<SMTExprRef
>(1);
573 static 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 (LLZK-tailored) dense data-flow analysis using the data-flow analysis framework.
Tracks a solver expression and an interval range for that expression.
ExpressionValue(llvm::SMTExprRef exprRef, const Interval &interval)
ExpressionValue withExpression(const llvm::SMTExprRef &newExpr) const
Return the current expression with a new SMT expression.
friend ExpressionValue neg(llvm::SMTSolverRef solver, const ExpressionValue &val)
friend ExpressionValue notOp(llvm::SMTSolverRef solver, const ExpressionValue &val)
const Interval & getInterval() const
friend ExpressionValue cmp(llvm::SMTSolverRef solver, boolean::CmpOp op, const ExpressionValue &lhs, const ExpressionValue &rhs)
ExpressionValue(const Field &f, llvm::SMTExprRef exprRef)
friend ExpressionValue sub(llvm::SMTSolverRef solver, const ExpressionValue &lhs, const ExpressionValue &rhs)
friend ExpressionValue mul(llvm::SMTSolverRef solver, const ExpressionValue &lhs, const ExpressionValue &rhs)
bool isBoolSort(llvm::SMTSolverRef solver) const
friend ExpressionValue fallbackUnaryOp(llvm::SMTSolverRef solver, mlir::Operation *op, const ExpressionValue &val)
friend ExpressionValue boolOr(llvm::SMTSolverRef solver, const ExpressionValue &lhs, const ExpressionValue &rhs)
friend ExpressionValue div(llvm::SMTSolverRef solver, felt::DivFeltOp op, const ExpressionValue &lhs, const ExpressionValue &rhs)
ExpressionValue withInterval(const Interval &newInterval) const
Return the current expression with a new interval.
void print(mlir::raw_ostream &os) const
bool operator==(const ExpressionValue &rhs) const
friend ExpressionValue add(llvm::SMTSolverRef solver, const ExpressionValue &lhs, const ExpressionValue &rhs)
friend ExpressionValue shiftRight(llvm::SMTSolverRef solver, const ExpressionValue &lhs, const ExpressionValue &rhs)
llvm::SMTExprRef getExpr() const
friend ExpressionValue fallbackBinaryOp(llvm::SMTSolverRef solver, mlir::Operation *op, const ExpressionValue &lhs, const ExpressionValue &rhs)
Computes a solver expression based on the operation, but computes a fallback interval (which is just ...
ExpressionValue(const Field &f, llvm::SMTExprRef exprRef, const llvm::DynamicAPInt &singleVal)
friend ExpressionValue bitAnd(llvm::SMTSolverRef solver, const ExpressionValue &lhs, const ExpressionValue &rhs)
friend ExpressionValue boolXor(llvm::SMTSolverRef solver, const ExpressionValue &lhs, const ExpressionValue &rhs)
friend ExpressionValue join(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...
friend mlir::raw_ostream & operator<<(mlir::raw_ostream &os, const ExpressionValue &e)
friend ExpressionValue boolAnd(llvm::SMTSolverRef solver, const ExpressionValue &lhs, const ExpressionValue &rhs)
const Field & getField() const
friend ExpressionValue mod(llvm::SMTSolverRef solver, const ExpressionValue &lhs, const ExpressionValue &rhs)
friend ExpressionValue shiftLeft(llvm::SMTSolverRef solver, const ExpressionValue &lhs, const ExpressionValue &rhs)
ExpressionValue & join(const ExpressionValue &)
Fold two expressions together when overapproximating array elements.
friend ExpressionValue intersection(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 boolNot(llvm::SMTSolverRef solver, const ExpressionValue &val)
Information about the prime finite field used for the interval analysis.
static const Field & getField(const char *fieldName)
Get a Field from a given field name string.
Maps mlir::Values to LatticeValues.
friend mlir::raw_ostream & operator<<(mlir::raw_ostream &os, const IntervalAnalysisLattice &l)
const ValueMap & getMap() const
mlir::DenseMap< mlir::Value, mlir::DenseMap< mlir::StringAttr, LatticeValue > > FieldMap
llvm::SetVector< ExpressionValue > ConstraintSet
IntervalAnalysisLatticeValue LatticeValue
ValueMap::iterator begin()
mlir::ChangeResult meet(const AbstractDenseLattice &) override
mlir::ChangeResult setValue(mlir::Value v, mlir::StringAttr f, ExpressionValue e)
mlir::DenseMap< mlir::Value, LatticeValue > ValueMap
mlir::ChangeResult addSolverConstraint(ExpressionValue e)
mlir::ChangeResult setValue(mlir::Value v, ExpressionValue e)
const ConstraintSet & getConstraints() const
void print(mlir::raw_ostream &os) const override
ValueMap::const_iterator end() const
mlir::ChangeResult setValue(mlir::Value v, const LatticeValue &val)
mlir::DenseMap< llvm::SMTExprRef, Interval > ExpressionIntervals
mlir::ChangeResult join(const AbstractDenseLattice &other) override
mlir::FailureOr< LatticeValue > getValue(mlir::Value v) const
ValueMap::const_iterator begin() const
mlir::FailureOr< Interval > findInterval(llvm::SMTExprRef expr) const
mlir::ChangeResult setInterval(llvm::SMTExprRef expr, const Interval &i)
mlir::FailureOr< LatticeValue > getValue(mlir::Value v, mlir::StringAttr f) const
mlir::LogicalResult visitOperation(mlir::Operation *op, const Lattice &before, Lattice *after) override
Visit an operation with the dense lattice before its execution.
void visitCallControlFlowTransfer(mlir::CallOpInterface call, dataflow::CallControlFlowAction action, const Lattice &before, Lattice *after) override
The interval analysis is intraprocedural only for now, so this control flow transfer function passes ...
llvm::SMTExprRef getOrCreateSymbol(const SourceRef &r)
Either return the existing SMT expression that corresponds to the SourceRef, or create one.
IntervalDataFlowAnalysis(mlir::DataFlowSolver &dataflowSolver, llvm::SMTSolverRef smt, const Field &f, bool propInputConstraints)
Intervals over a finite field.
mlir::DataFlowSolver solver
ModuleAnalysis(mlir::Operation *op)
ModuleIntervalAnalysis(mlir::Operation *op)
virtual ~ModuleIntervalAnalysis()=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
StructAnalysis(mlir::Operation *op)
Assert that this analysis is being run on a StructDefOp and initializes the analysis with the current...
virtual ~StructIntervalAnalysis()=default
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.
LLZK: This class has been ported so that it can inherit from our port of the AbstractDenseForwardData...
mlir::dataflow::AbstractDenseLattice AbstractDenseLattice
mlir::dataflow::CallControlFlowAction CallControlFlowAction
void ensure(bool condition, const llvm::Twine &errMsg)
APSInt toAPSInt(const DynamicAPInt &i)
ExpressionValue mod(llvm::SMTSolverRef solver, const ExpressionValue &lhs, const ExpressionValue &rhs)
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