aboutsummaryrefslogtreecommitdiffstats
path: root/libevmasm/ExpressionClasses.cpp
blob: fc283b0bcef7bb49aa7172d3c8b158e7ba70bfc0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
/*
    This file is part of solidity.

    solidity is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    solidity is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with solidity.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * @file ExpressionClasses.cpp
 * @author Christian <c@ethdev.com>
 * @date 2015
 * Container for equivalence classes of expressions for use in common subexpression elimination.
 */

#include <libevmasm/ExpressionClasses.h>
#include <utility>
#include <tuple>
#include <functional>
#include <boost/range/adaptor/reversed.hpp>
#include <boost/noncopyable.hpp>
#include <libevmasm/Assembly.h>
#include <libevmasm/CommonSubexpressionEliminator.h>
#include <libevmasm/SimplificationRules.h>

using namespace std;
using namespace dev;
using namespace dev::eth;


bool ExpressionClasses::Expression::operator<(ExpressionClasses::Expression const& _other) const
{
    assertThrow(!!item && !!_other.item, OptimizerException, "");
    auto type = item->type();
    auto otherType = _other.item->type();
    if (type != otherType)
        return type < otherType;
    else if (type == Operation)
    {
        auto instr = item->instruction();
        auto otherInstr = _other.item->instruction();
        return std::tie(instr, arguments, sequenceNumber) <
            std::tie(otherInstr, _other.arguments, _other.sequenceNumber);
    }
    else
        return std::tie(item->data(), arguments, sequenceNumber) <
            std::tie(_other.item->data(), _other.arguments, _other.sequenceNumber);
}

ExpressionClasses::Id ExpressionClasses::find(
    AssemblyItem const& _item,
    Ids const& _arguments,
    bool _copyItem,
    unsigned _sequenceNumber
)
{
    Expression exp;
    exp.id = Id(-1);
    exp.item = &_item;
    exp.arguments = _arguments;
    exp.sequenceNumber = _sequenceNumber;

    if (SemanticInformation::isCommutativeOperation(_item))
        sort(exp.arguments.begin(), exp.arguments.end());

    if (SemanticInformation::isDeterministic(_item))
    {
        auto it = m_expressions.find(exp);
        if (it != m_expressions.end())
            return it->id;
    }

    if (_copyItem)
        exp.item = storeItem(_item);

    ExpressionClasses::Id id = tryToSimplify(exp);
    if (id < m_representatives.size())
        exp.id = id;
    else
    {
        exp.id = m_representatives.size();
        m_representatives.push_back(exp);
    }
    m_expressions.insert(exp);
    return exp.id;
}

void ExpressionClasses::forceEqual(
    ExpressionClasses::Id _id,
    AssemblyItem const& _item,
    ExpressionClasses::Ids const& _arguments,
    bool _copyItem
)
{
    Expression exp;
    exp.id = _id;
    exp.item = &_item;
    exp.arguments = _arguments;

    if (SemanticInformation::isCommutativeOperation(_item))
        sort(exp.arguments.begin(), exp.arguments.end());

    if (_copyItem)
        exp.item = storeItem(_item);

    m_expressions.insert(exp);
}

ExpressionClasses::Id ExpressionClasses::newClass(SourceLocation const& _location)
{
    Expression exp;
    exp.id = m_representatives.size();
    exp.item = storeItem(AssemblyItem(UndefinedItem, (u256(1) << 255) + exp.id, _location));
    m_representatives.push_back(exp);
    m_expressions.insert(exp);
    return exp.id;
}

bool ExpressionClasses::knownToBeDifferent(ExpressionClasses::Id _a, ExpressionClasses::Id _b)
{
    // Try to simplify "_a - _b" and return true iff the value is a non-zero constant.
    return knownNonZero(find(Instruction::SUB, {_a, _b}));
}

bool ExpressionClasses::knownToBeDifferentBy32(ExpressionClasses::Id _a, ExpressionClasses::Id _b)
{
    // Try to simplify "_a - _b" and return true iff the value is at least 32 away from zero.
    u256 const* v = knownConstant(find(Instruction::SUB, {_a, _b}));
    // forbidden interval is ["-31", 31]
    return v && *v + 31 > u256(62);
}

bool ExpressionClasses::knownZero(Id _c)
{
    return Pattern(u256(0)).matches(representative(_c), *this);
}

bool ExpressionClasses::knownNonZero(Id _c)
{
    return Pattern(u256(0)).matches(representative(find(Instruction::ISZERO, {_c})), *this);
}

u256 const* ExpressionClasses::knownConstant(Id _c)
{
    map<unsigned, Expression const*> matchGroups;
    Pattern constant(Push);
    constant.setMatchGroup(1, matchGroups);
    if (!constant.matches(representative(_c), *this))
        return nullptr;
    return &constant.d();
}

AssemblyItem const* ExpressionClasses::storeItem(AssemblyItem const& _item)
{
    m_spareAssemblyItems.push_back(make_shared<AssemblyItem>(_item));
    return m_spareAssemblyItems.back().get();
}

string ExpressionClasses::fullDAGToString(ExpressionClasses::Id _id) const
{
    Expression const& expr = representative(_id);
    stringstream str;
    str << dec << expr.id << ":";
    if (expr.item)
    {
        str << *expr.item << "(";
        for (Id arg: expr.arguments)
            str << fullDAGToString(arg) << ",";
        str << ")";
    }
    else
        str << " UNIQUE";
    return str.str();
}

ExpressionClasses::Id ExpressionClasses::tryToSimplify(Expression const& _expr, bool _secondRun)
{
    static Rules rules;

    if (
        !_expr.item ||
        _expr.item->type() != Operation ||
        !SemanticInformation::isDeterministic(*_expr.item)
    )
        return -1;

    if (auto match = rules.findFirstMatch(_expr, *this))
    {
        // Debug info
        //cout << "Simplifying " << *_expr.item << "(";
        //for (Id arg: _expr.arguments)
        //  cout << fullDAGToString(arg) << ", ";
        //cout << ")" << endl;
        //cout << "with rule " << match->first.toString() << endl;
        //ExpressionTemplate t(match->second());
        //cout << "to " << match->second().toString() << endl;
        return rebuildExpression(ExpressionTemplate(match->second(), _expr.item->location()));
    }

    if (!_secondRun && _expr.arguments.size() == 2 && SemanticInformation::isCommutativeOperation(*_expr.item))
    {
        Expression expr = _expr;
        swap(expr.arguments[0], expr.arguments[1]);
        return tryToSimplify(expr, true);
    }

    return -1;
}

ExpressionClasses::Id ExpressionClasses::rebuildExpression(ExpressionTemplate const& _template)
{
    if (_template.hasId)
        return _template.id;

    Ids arguments;
    for (ExpressionTemplate const& t: _template.arguments)
        arguments.push_back(rebuildExpression(t));
    return find(_template.item, arguments);
}