#include <libyul/optimiser/KnowledgeBase.h>
#include <libyul/AST.h>
#include <libyul/Utilities.h>
#include <libyul/optimiser/SimplificationRules.h>
#include <libyul/optimiser/DataFlowAnalyzer.h>
#include <libsolutil/CommonData.h>
#include <variant>
using namespace std;
using namespace solidity;
using namespace solidity::yul;
bool KnowledgeBase::knownToBeDifferent(YulString _a, YulString _b)
{
if (optional<u256> difference = differenceIfKnownConstant(_a, _b))
return difference != 0;
Expression expr2 = simplify(FunctionCall{{}, {{}, "eq"_yulstring}, util::make_vector<Expression>(Identifier{{}, _a}, Identifier{{}, _b})});
if (holds_alternative<Literal>(expr2))
return valueOfLiteral(std::get<Literal>(expr2)) == 0;
return false;
}
optional<u256> KnowledgeBase::differenceIfKnownConstant(YulString _a, YulString _b)
{
Expression expr1 = simplify(FunctionCall{{}, {{}, "sub"_yulstring}, util::make_vector<Expression>(Identifier{{}, _a}, Identifier{{}, _b})});
if (Literal const* value = get_if<Literal>(&expr1))
return valueOfLiteral(*value);
return {};
}
bool KnowledgeBase::knownToBeDifferentByAtLeast32(YulString _a, YulString _b)
{
if (optional<u256> difference = differenceIfKnownConstant(_a, _b))
return difference >= 32 && difference <= u256(0) - 32;
return false;
}
bool KnowledgeBase::knownToBeZero(YulString _a)
{
return valueIfKnownConstant(_a) == u256{};
}
optional<u256> KnowledgeBase::valueIfKnownConstant(YulString _a)
{
if (AssignedValue const* value = m_variableValues(_a))
if (Literal const* literal = get_if<Literal>(value->value))
return valueOfLiteral(*literal);
return {};
}
Expression KnowledgeBase::simplify(Expression _expression)
{
m_counter = 0;
return simplifyRecursively(move(_expression));
}
Expression KnowledgeBase::simplifyRecursively(Expression _expression)
{
if (m_counter++ > 100)
return _expression;
if (holds_alternative<FunctionCall>(_expression))
for (Expression& arg: std::get<FunctionCall>(_expression).arguments)
arg = simplifyRecursively(arg);
if (auto match = SimplificationRules::findFirstMatch(_expression, m_dialect, m_variableValues))
return simplifyRecursively(match->action().toExpression(debugDataOf(_expression)));
return _expression;
}