summaryrefslogtreecommitdiffstats
path: root/src/shader_recompiler/backend/glasm/reg_alloc.cpp
blob: 55e8107e9c017feec84d9c07937aef48ab90a5e0 (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
// Copyright 2021 yuzu Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.

#include <string>

#include <fmt/format.h>

#include "shader_recompiler/backend/glasm/emit_context.h"
#include "shader_recompiler/backend/glasm/reg_alloc.h"
#include "shader_recompiler/exception.h"
#include "shader_recompiler/frontend/ir/value.h"

namespace Shader::Backend::GLASM {
namespace {
std::string Representation(Id id) {
    if (id.is_condition_code != 0) {
        throw NotImplementedException("Condition code");
    }
    if (id.is_spill != 0) {
        throw NotImplementedException("Spilling");
    }
    const u32 index{static_cast<u32>(id.index)};
    return fmt::format("R{}.x", index);
}

std::string ImmValue(const IR::Value& value) {
    switch (value.Type()) {
    case IR::Type::U1:
        return value.U1() ? "-1" : "0";
    case IR::Type::U32:
        return fmt::format("{}", value.U32());
    case IR::Type::F32:
        return fmt::format("{}", value.F32());
    default:
        throw NotImplementedException("Immediate type", value.Type());
    }
}
} // Anonymous namespace

std::string RegAlloc::Define(IR::Inst& inst) {
    const Id id{Alloc()};
    inst.SetDefinition<Id>(id);
    return Representation(id);
}

std::string RegAlloc::Consume(const IR::Value& value) {
    if (value.IsImmediate()) {
        return ImmValue(value);
    } else {
        return Consume(*value.InstRecursive());
    }
}

std::string RegAlloc::Consume(IR::Inst& inst) {
    const Id id{inst.Definition<Id>()};
    inst.DestructiveRemoveUsage();
    if (!inst.HasUses()) {
        Free(id);
    }
    return Representation(inst.Definition<Id>());
}

Id RegAlloc::Alloc() {
    for (size_t reg = 0; reg < NUM_REGS; ++reg) {
        if (register_use[reg]) {
            continue;
        }
        num_used_registers = std::max(num_used_registers, reg + 1);
        register_use[reg] = true;
        return Id{
            .index = static_cast<u32>(reg),
            .is_spill = 0,
            .is_condition_code = 0,
        };
    }
    throw NotImplementedException("Register spilling");
}

void RegAlloc::Free(Id id) {
    if (id.is_spill != 0) {
        throw NotImplementedException("Free spill");
    }
    register_use[id.index] = false;
}

} // namespace Shader::Backend::GLASM