MIXAL
machine_arithmetic.cpp
Go to the documentation of this file.
1 #include <iostream>
2 #include "machine.h"
3 
9 namespace mixal {
10 
15 void Computer::executeADD(const InstructionWord& instruction) {
16  int32_t valueA = rA.value();
17  ComputerWord word;
18  int address = getIndexedAddress(instruction, true);
19  copyToRegister5(instruction, memory[address], &word);
20  int32_t valueM = word.value();
21  int32_t result = valueA + valueM;
22  rA.set(checkRange(result));
23 }
24 
29 void Computer::executeSUB(const InstructionWord& instruction) {
30  int32_t valueA = rA.value();
31  ComputerWord word;
32  int address = getIndexedAddress(instruction, true);
33  copyToRegister5(instruction, memory[address], &word);
34  word.negative = !word.negative;
35  int32_t valueM = word.value();
36  int32_t result = valueA + valueM;
37  rA.set(checkRange(result));
38 }
39 
44 void Computer::executeMUL(const InstructionWord& instruction) {
45  int32_t valueA = rA.value();
46  ComputerWord word;
47  int address = getIndexedAddress(instruction, true);
48  copyToRegister5(instruction, memory[address], &word);
49  int32_t valueM = word.value();
50  int64_t result = static_cast<int64_t>(valueA) * static_cast<int64_t>(valueM);
51  rA.set(result / (1 << 30));
52  rX.set(result % (1 << 30));
53 }
54 
63 void Computer::executeDIV(const InstructionWord& instruction) {
64  int32_t valueA = std::abs(rA.value());
65  int32_t valueX = std::abs(rX.value());
66  int64_t dividend = (static_cast<int64_t>(valueA) << 30) + static_cast<int64_t>(valueX);
67  if (rA.negative) {
68  dividend = -dividend;
69  }
70  ComputerWord word;
71  int address = getIndexedAddress(instruction, true);
72  copyToRegister5(instruction, memory[address], &word);
73  int32_t divisor = word.value();
74  if (divisor == 0) {
75  throw RuntimeError(_lineOffset, "Divisor cannot be 0");
76  }
77  int64_t quotient = dividend / divisor;
78  if (std::abs(quotient) >= (1 << 30)) {
79  overflow = true;
80  quotient %= (1 << 30);
81  }
82  int32_t remainder = dividend % divisor;
83  rA.set(static_cast<int32_t>(quotient));
84  rX.set(remainder);
85 }
86 
87 }; // namespace mixal
mixal::Computer::rX
Register5 rX
Definition: machine.h:32
mixal::Computer::memory
ComputerWord memory[NUM_MEMORY]
Definition: machine.h:38
machine.h
The virtual machine.
mixal::Computer::overflow
bool overflow
Definition: machine.h:35
mixal::ComputerWord::value
int32_t value() const
Definition: memory.cpp:132
mixal::ComputerWord::set
void set(int32_t value)
Definition: memory.cpp:178
mixal::Computer::rA
Register5 rA
Definition: machine.h:32