The post has been translated automatically. Original language: Russian
When Donald Knuth created MIX for the "Art of Programming," he didn't need a copy of any particular computer. We needed a fairly simple and yet complete architecture on which to explain algorithms, memory, registers, transitions, and machine instructions.
That's why MIX is interesting decades later, not so much for its age as for its design approach. This is an attempt to first define an understandable computing model, and only then express the necessary operations through it.
In MIX, the machine word consists of five bytes and a sign, the memory contains 4,000 words, and the architecture itself uses several types of specialized registers. The command is also a machine word and contains an address, an index register number, a modifier field, and an operation code. The modifier can, in particular, indicate which part of the word to work with.
Memora8 is designed quite differently. This is a 32-bit processor designed for real hardware implementation. In the version under consideration, it has 32 general-purpose registers, a fixed 32-bit instruction word, and 28 valid commands. Four more opcode values are left unused.
At first glance, there is little in common between the two machines. MIX has its own data formats, specialized registers, and work with word fields that is unusual for today's programmer. There is no need to reproduce these solutions in Memora8. The connection between them is deeper — in the very way you look at the processor architecture.
Not to copy the commands, but to understand their purpose
When studying the old architecture, it is easy to fall into the trap of literal comparison: find the MIX command, then look for its counterpart in Memora8. This approach explains little, because over the decades not only the element base has changed, but also the idea of what kind of work the equipment should do.
Registers are a good example. The MIX uses an accumulator A, an extension X, six index registers, and a separate jump register J. Each of them has its own architectural role. This makes the device of the machine clearly visible to the programmer, but at the same time fixes many special cases in the architecture itself.
In Memora8, a different path is chosen. There are 32 identical 32-bit general-purpose registers, and most of their roles are already determined by the program and the calling convention. The special behavior is actually reserved only for r0: when reading, it always returns zero, and writing to it does not change the processor state.
This is no longer a borrowing of the MIX design, but a rethinking of the task itself. Knuth made the assignment of registers explicit through the architecture. In Memora8, on the contrary, a significant part of the specialization is removed from the hardware so that the basic register mechanism remains uniform.
What does a minimal car mean?
MIX is not a primitive processor. On the contrary, its command system allows you to perform quite complex actions, including working with individual parts of a machine word. The same general instruction format gets additional meaning through a modifier field. Due to this, the architecture remains compact in form, but very expressive in capabilities.
In Memora8, the idea of compactness develops in a different direction. It uses a small set of 28 commands, with arithmetic, logical operations, memory management, and flow control divided into simple actions.
For example, the comparison is not hidden inside the conditional transition. The CMP and CMPI instructions generate the result of the comparison and write it to a regular register. After that, the program can select the desired condition with a logical operation and use BNZ or BEQZ.
This option sometimes requires several commands where a more complex processor could do with one. But the hardware model is becoming noticeably more transparent: one team compares, another processes the result, and the third decides whether to change the execution process.
This clearly shows the main difference in approaches. In MIX, complexity is often placed inside the instruction itself. In Memora8, a combination of a small number of simple mechanisms is preferred.
Why is the FPGA changing the way it looks at the instruction set?
MIX was created as an abstract computing machine. It had to be specific enough to write and execute programs on it, but Knuth didn't have to put his decoder, registers, and data paths into a specific chip.
This is a fundamental difference for Memora8. The architectural solution quickly becomes a real digital circuit. The instruction format determines the decoder, the number of data sources affects the connections between nodes, and an additional special case can go through several processor stages.
Therefore, the fixed 32-bit instruction in Memora8 is chosen not only for the convenience of the programmer. It simplifies the selection and analysis of the command. Several formats use the same positions of the main fields, so the hardware does not have to first determine the length of the instruction or assemble it from several parts.
The same principle is seen in the Memora8 pipeline. The command sequentially goes through five stages: sampling, reading registers, working with memory, execution and final fixation of the result. The architectural state changes only at the last stage. Due to this, the internal execution and the result visible to the program are separated quite clearly.
It is already clearly visible here that minimalism is not just a small number of teams. It is more important to limit the number of different rules by which these commands pass through the processor.
From MIX fields to simple Memora8 formats
The difference between the epochs is particularly evident in the format of the commands.
MIX allows you to specify an address, an index case, and a modifier that can change the meaning of an operation or select a specific field of a machine word. For the Knuth architecture, this is a powerful universal mechanism: a single command is able to express quite a lot of information at once.
Memora8 uses a different compromise. The instruction always occupies 32 bits, and its fields depend on several simple formats. There are options for operations between registers, direct value commands, transitions, and memory accesses.
As a result, an individual team can do less, but its structure is easier to trace from the original machine word to the hardware execution. For a processor that is actually implemented in programmable logic and tested at the digital circuit level, this is an essential property.
It turns out an interesting inversion. MIX aims to make one instruction expressive enough. Memora8 strives to make each instruction fairly simple.
What's left of the MIX in the end
No ready-made registers, word formats, or machine instruction sets were transferred from MIX to Memora8. Most of Knuth's specific solutions for a modern small 32-bit processor would be a limitation rather than an advantage.
But a more important principle has been preserved: architecture should be small enough to be fully understood.
This means that every opportunity needs to be found consciously. If an operation can be obtained by combining existing commands, it is worth evaluating this option first, rather than immediately expanding the processor. If the special role of the register can be defined at the level of program agreement, it is not necessary to fix it in the hardware. If multiple actions can be performed through a single regular data path, this is often more valuable than saving a single machine instruction.
In this sense, MIX turned out to be a good reference point for Memora8 rather than a copy model. The Knuth architecture allows us to see how a complete computer can be built from a relatively small number of understandable mechanisms. Memora8 asks the same question under different conditions.: which of these mechanisms should really exist inside a modern processor implemented on an FPGA, and which are more reasonable to express by simpler means.
Therefore, it is more interesting to compare MIX and Memora8 not according to the command table. It is much more useful to trace the fate of architectural ideas: why Knuth came up with a certain solution, what task it solved, and what the same task turns into when a real digital circuit is designed instead of an imaginary machine.
This is exactly the comparison this series of articles is dedicated to.
Когда Дональд Кнут создавал MIX для «Искусства программирования», ему требовалась не копия какой-либо конкретной вычислительной машины. Нужна была достаточно простая и при этом полноценная архитектура, на которой можно объяснять алгоритмы, работу памяти, регистров, переходов и машинных команд.
Поэтому MIX интересен спустя десятилетия не столько своим возрастом, сколько подходом к проектированию. Это попытка сначала определить понятную модель вычислений, а уже затем выразить через неё необходимые операции.
В MIX машинное слово состоит из пяти байтов и знака, память содержит 4000 слов, а сама архитектура использует несколько типов специализированных регистров. Команда также является машинным словом и содержит адрес, номер индексного регистра, поле-модификатор и код операции. Модификатор может, в частности, указывать, с какой частью слова следует работать.
Memora8 устроен совсем иначе. Это 32-битный процессор, рассчитанный на настоящую аппаратную реализацию. В рассматриваемой версии у него 32 регистра общего назначения, фиксированное 32-битное слово инструкции и 28 действующих команд. Ещё четыре значения кода операции оставлены незадействованными.
На первый взгляд общего между двумя машинами немного. У MIX свои форматы данных, специализированные регистры и необычная для сегодняшнего программиста работа с полями слова. В Memora8 нет необходимости воспроизводить эти решения. Связь между ними находится глубже — в самом способе смотреть на архитектуру процессора.
Не копировать команды, а понять их назначение
При изучении старой архитектуры легко попасть в ловушку буквального сравнения: найти команду MIX, затем искать её аналог в Memora8. Такой подход мало что объясняет, потому что за десятилетия изменилась не только элементная база, но и представление о том, какую работу следует выполнять аппаратуре.
Хороший пример — регистры. MIX использует аккумулятор A, расширение X, шесть индексных регистров и отдельный регистр перехода J. У каждого из них есть своя архитектурная роль. Это делает устройство машины хорошо видимым программисту, но одновременно закрепляет в самой архитектуре множество специальных случаев.
В Memora8 выбран другой путь. Здесь 32 одинаковых 32-битных регистра общего назначения, а большинство их ролей определяется уже программой и соглашением о вызовах. Особое поведение оставлено фактически только за r0: при чтении он всегда возвращает ноль, а запись в него не меняет состояние процессора.
Это уже не заимствование конструкции MIX, а переосмысление самой задачи. Кнут сделал назначение регистров явным через архитектуру. В Memora8, наоборот, значительная часть специализации вынесена из аппаратуры, чтобы основной регистровый механизм оставался единообразным.
Что значит минимальная машина
MIX нельзя назвать примитивным процессором. Напротив, его система команд позволяет выполнять довольно сложные действия, включая работу с отдельными частями машинного слова. Один и тот же общий формат инструкции получает дополнительный смысл через поле-модификатор. Благодаря этому архитектура остаётся компактной по форме, но весьма выразительной по возможностям.
В Memora8 идея компактности развивается в другом направлении. Здесь используется небольшой набор из 28 команд, причём арифметика, логические операции, работа с памятью и управление потоком разделены на простые действия.
Например, сравнение не скрыто внутри условного перехода. Инструкции CMP и CMPI формируют результат сравнения и записывают его в обычный регистр. После этого программа может выделить нужное условие логической операцией и использовать BNZ или BEQZ.
Такой вариант требует иногда нескольких команд там, где более сложный процессор мог бы обойтись одной. Но аппаратная модель становится заметно прозрачнее: одна команда сравнивает, другая обрабатывает результат, третья решает, менять ли ход исполнения.
Это хорошо показывает главное различие подходов. В MIX сложность часто помещается внутрь самой инструкции. В Memora8 предпочтение отдаётся сочетанию небольшого количества простых механизмов.
Почему FPGA меняет взгляд на систему команд
MIX был создан как абстрактная вычислительная машина. Он должен был быть достаточно определённым, чтобы на нём можно было писать и выполнять программы, но Кнуту не приходилось укладывать его декодер, регистры и пути данных в конкретную микросхему.
Для Memora8 это принципиальное отличие. Архитектурное решение достаточно быстро становится реальной цифровой схемой. Формат инструкции определяет декодер, количество источников данных влияет на соединения между узлами, а дополнительный специальный случай может пройти через несколько стадий процессора.
Поэтому фиксированная 32-битная инструкция в Memora8 выбрана не только ради удобства программиста. Она упрощает выборку и разбор команды. Несколько форматов используют одни и те же позиции основных полей, поэтому аппаратуре не приходится сначала определять длину инструкции или собирать её из нескольких частей.
Тот же принцип виден в конвейере Memora8. Команда последовательно проходит пять стадий: выборку, чтение регистров, работу с памятью, исполнение и окончательную фиксацию результата. Архитектурное состояние изменяется только на последней стадии. Благодаря этому внутреннее выполнение и видимый программе результат разделены достаточно чётко.
Здесь уже хорошо заметно, что минимальность — это не просто малое количество команд. Важнее ограничить число различных правил, по которым эти команды проходят через процессор.
От полей MIX к простым форматам Memora8
Особенно наглядно различие эпох видно в формате команд.
MIX позволяет указать адрес, индексный регистр и модификатор, который может изменить смысл операции или выбрать определённое поле машинного слова. Для архитектуры Кнута это мощный универсальный механизм: одна команда способна сразу выразить довольно много информации.
Memora8 использует другой компромисс. Инструкция всегда занимает 32 бита, а её поля зависят от нескольких простых форматов. Есть варианты для операций между регистрами, команд с непосредственным значением, переходов и обращения к памяти.
В результате отдельная команда умеет меньше, но её устройство легче проследить от исходного машинного слова до аппаратного выполнения. Для процессора, который реально реализуется в программируемой логике и проверяется на уровне цифровой схемы, это существенное свойство.
Получается интересная инверсия. MIX стремится сделать одну инструкцию достаточно выразительной. Memora8 стремится сделать каждую инструкцию достаточно простой.
Что в итоге осталось от MIX
От MIX в Memora8 не переходили готовые регистры, форматы слова или набор машинных команд. Большинство конкретных решений Кнута для современного небольшого 32-битного процессора было бы скорее ограничением, чем преимуществом.
Но сохранился более важный принцип: архитектура должна быть достаточно небольшой, чтобы её можно было понимать целиком.
Это означает, что каждой возможности нужно находить место осознанно. Если операция может быть получена сочетанием уже существующих команд, стоит сначала оценить именно этот вариант, а не немедленно расширять процессор. Если специальную роль регистра можно определить на уровне соглашения программ, не обязательно закреплять её в аппаратуре. Если несколько действий можно провести через один регулярный путь данных, это часто ценнее, чем экономия одной машинной инструкции.
В этом смысле MIX оказался для Memora8 не образцом для копирования, а хорошей точкой отсчёта. Архитектура Кнута позволяет увидеть, как можно построить законченную вычислительную машину из относительно небольшого количества понятных механизмов. Memora8 задаёт тот же вопрос уже в других условиях: какие из этих механизмов действительно должны существовать внутри современного процессора, реализуемого на FPGA, а какие разумнее выразить более простыми средствами.
Поэтому сравнивать MIX и Memora8 интереснее не по таблице команд. Гораздо полезнее проследить судьбу архитектурных идей: зачем определённое решение появилось у Кнута, какую задачу оно решало и во что превращается та же задача, когда вместо воображаемой машины проектируется реальная цифровая схема.
Именно этому сравнению посвящена эта серия статей.