summaryrefslogtreecommitdiff
path: root/emulator.cpp
blob: 607ec63d4f7c9e8d5cda21dc5268afe194794f40 (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
93
94
95
96
97
98
99
100
101
102
103

#include <iostream>
#include <assert.h>

#include "emulator.h"

#include "program_loader.h"
#include "instruction.h"
#include "program.h"
#include "register_address.h"

emulator::emulator(
	program_loader * loader,
	int num_temp_regs,
	int num_const_regs,
	int num_out_regs)
	:
	m_loader(loader),
	m_temp_regs(num_temp_regs),
	m_const_regs(num_const_regs, new float_value()),
	m_out_regs(num_out_regs)
	{ }

bool
emulator::run()
{
	program * p = m_loader->load();
	if (!p) {
		std::cerr << "Could not load program\n";
		return false;
	}
	m_immediate_regs = p->m_immediate_regs;
	std::vector<instruction *>::iterator it;
	for(it = p->m_instructions.begin();
					it < p->m_instructions.end(); ++it) {
		(*it)->execute(*this);
	}
	return true;
}

void
emulator::set_constants(float value)
{
	std::vector<float_value *>::iterator it;
	for(it = m_const_regs.begin(); it < m_const_regs.end(); ++it) {
		(*it)->set_value(value);
	}
}

value *
emulator::get_value(register_address addr)
{
	unsigned int index = addr.to_int();

	switch(addr.m_type) {
	case REGISTER_TYPE_TEMP: return m_temp_regs[index]->clone();
	case REGISTER_TYPE_CONST:
	{
		float_value * val = m_const_regs[index];

		if (val->m_has_value) {
			return new float_value(*val);
		} else {
			return new const_value(addr, val);
		}
	}
	case REGISTER_TYPE_OUT: return m_out_regs[index]->clone();
	case REGISTER_TYPE_IMMEDIATE: return m_immediate_regs[index]->clone();
	default:
		assert(0);
		return NULL;
	}
}

void
emulator::set_value(
	register_address addr,
	value * val)
{
	unsigned int index = addr.to_int();

	switch(addr.m_type) {
	case REGISTER_TYPE_TEMP:
		delete m_temp_regs[index];
		m_temp_regs[index] = val;
		break;
	case REGISTER_TYPE_OUT:
		delete m_out_regs[index];
		m_out_regs[index] = val;
		break;
	default:
		assert(0);
	}
}

value *
emulator::get_output_value(unsigned int index)
{
	if (index >= m_out_regs.size() || !m_out_regs[index]) {
		return NULL;
	}
	return m_out_regs[index]->simplify();
}