dead_code_elimination.cpp 1.87 KB
Newer Older
Paul's avatar
Paul committed
1
2
3
4
5
#include <migraph/dead_code_elimination.hpp>
#include <migraph/program.hpp>
#include <migraph/instruction.hpp>
#include <migraph/iterator_for.hpp>
#include <migraph/functional.hpp>
Paul's avatar
Paul committed
6
#include <migraph/ranges.hpp>
Paul's avatar
Paul committed
7
8
9

namespace migraph {

Paul's avatar
Paul committed
10
template <class Range, class Iterator>
Paul's avatar
Paul committed
11
12
std::ptrdiff_t bidistance(const Range& r, Iterator start, Iterator last)
{
Paul's avatar
Paul committed
13
    auto start_forward   = start;
Paul's avatar
Paul committed
14
    auto start_backwards = start;
Paul's avatar
Paul committed
15
    std::size_t n        = 0;
Paul's avatar
Paul committed
16
17
18
    while(start_forward != last and start_backwards != last)
    {
        n++;
Paul's avatar
Paul committed
19
20
21
22
        if(start_forward != r.end())
            start_forward++;
        if(start_backwards != r.begin())
            start_backwards--;
Paul's avatar
Paul committed
23
24
25
26
27
28
29
    }
    if(start_forward == last)
        return n;
    else
        return -n;
}

Paul's avatar
Paul committed
30
31
void dead_code_elimination::apply(program& p) const
{
32
33
    auto last = std::prev(p.end());
    for(auto ins : iterator_for(p))
Paul's avatar
Paul committed
34
    {
Paul's avatar
Paul committed
35
36
37
38
        // Skip the first instruction, since we always process the previous
        // instruction
        if(ins == p.begin())
            continue;
39
        const auto i = std::prev(ins);
Paul's avatar
Paul committed
40
        // Skip the last instruction
41
        if(i == last)
Paul's avatar
Paul committed
42
            break;
Paul's avatar
Paul committed
43
44
45
46
        // Skip instruction with empty shape as output unless its a builtin
        if(i->get_shape().elements() == 0 and not(i->name().front() == '@'))
            continue;
        assert(bidistance(p, i, last) > 0);
47
48
        fix([&](auto self, auto leaf) {
            assert(p.has_instruction(leaf));
Paul's avatar
Paul committed
49
            if(leaf->outputs().empty())
Paul's avatar
Paul committed
50
            {
Paul's avatar
Paul committed
51
                auto args = leaf->inputs();
Paul's avatar
Paul committed
52
                leaf->clear_arguments();
Paul's avatar
Paul committed
53
54
                assert(bidistance(p, last, leaf) < 0);
                assert(leaf != ins);
55
                p.move_instruction(leaf, p.end());
Paul's avatar
Paul committed
56
                for(auto arg : args)
Paul's avatar
Paul committed
57
58
                    self(arg);
            }
59
        })(i);
Paul's avatar
Paul committed
60
    }
61
    p.remove_instructions(std::next(last), p.end());
Paul's avatar
Paul committed
62
63
64
}

} // namespace migraph