summaryrefslogtreecommitdiffhomepage
path: root/asm/assembler.h
blob: 3d3e9a9148204d00495a18ad6738e9afeb18c3bf (plain)
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
#pragma once

#include "chunk.h"

#include <boost/endian/conversion.hpp>

#include <any>
#include <functional>
#include <iostream>
#include <memory>
#include <string>
#include <unordered_map>

using AsmArgs = std::vector<std::any>;
using FactoryFunction = std::function<std::shared_ptr<Op>(AsmArgs&)>;

// mnemonic: mnemonic including argument types
bool registerOp(const std::string& mnemonic, FactoryFunction f);

// Create Op from a registered mnemonic
// mnemonic: just the mnemonic name
std::shared_ptr<Op> makeOp(const std::string& mnemonic, AsmArgs& args);

// overload for empty list of arguments
std::shared_ptr<Op> makeOp(const std::string& mnemonic);

std::shared_ptr<Label> makeLabel(const std::string& name);
std::shared_ptr<Data> makeData(const std::vector<uint8_t>& data);

template<typename T>
std::string mangleNameOne(const std::string& s)
{
 return s + "_" + typeid(T).name();
}

template<typename T, typename... Targs>
std::string mangleName(const std::string& s)
{
 if constexpr (sizeof...(Targs) == 0)
  return mangleNameOne<T>(s);
 else
  return mangleName<Targs...>(s + "_" + typeid(T).name());
}

std::string mangleName(const std::string& s, AsmArgs& args);

class Immediate8
{
public:
 Immediate8(uint8_t value): m_value(value) {}
 uint8_t value() {return m_value;}
 std::vector<uint8_t> getCode() {return {m_value};};

private:
 uint8_t m_value;
};

class Immediate32
{
public:
 Immediate32(uint32_t value): m_value(value) {}
 uint32_t value() { return m_value; }
 std::vector<uint8_t> getCode() {
  std::vector<uint8_t> result(size_t(4));
  *(reinterpret_cast<uint32_t*>(result.data())) = boost::endian::native_to_little(m_value);
  return result;
 };

private:
 uint32_t m_value;
};

class Register32
{
public:
 Register32(const std::string& name): m_name(name) {}
 std::string name() { return m_name; }

private:
 std::string m_name;
};

class Register64
{
public:
 Register64(const std::string& name): m_name(name) {}
 std::string name() { return m_name; }

private:
 std::string m_name;
};