r/AskComputerScience • u/BakedFilosofer • Nov 14 '20
How does machine code interact with the hardware? (Info in comment)
9
u/BakedFilosofer Nov 14 '20
Disclaimer: I'm not a CS major, just passionate about computers.
So I'm reading the book Code by Charles Petzold and I've reached the part where he explains how a basic ALU works.
I get the concept of operation codes and how they help us interest with the machine. However what the book doesn't seem to explain is how those operation codes affect the actual hardware.
For example how does the operation code for ADD tell the whole system to take take the data out of the RAM and put it into the 8-bit adder.
the illustration shows a vague arrow pointing somewhere without explaining how the actual operation codes affect the system.
Can someone elaborate?
9
u/Bosco89 Nov 14 '20
The ALU itself does not fetch data on its own. There are other components whose job is to:
fetch the instruction
decode the instruction and retrieve other addressed data
execute the instruction by activating the appropriate components (eg. The ALU)
store the results where necessary
2
4
u/Horny20yrold Nov 14 '20
It is several operations chained together, all working together in parallel. First there is the "fetching logic", which is simply a counter (a hardware circuit that switch value each clock tick) that increments from the start of the code to the end of the code, each time giving it's value to the RAM which replies with the value stored at that location. So for example, imagine an 8 byte RAM that stores nothing but 1-byte opcodes. The fetching logic for that RAM is a 3 bit counter that continually counts from 0 to 7, and "pumps" the value it finds at that location in the RAM. There is a lot of details to gloss over: The RAM typically contains (at least) both data and code, so you need to divide it into "Segments" and the fetching logic needs to start counting from the start of the code segment. Also, a lot of instruction sets aren't "fixed length", one opcode might be 1 byte, another might be 4. The fetching logic must contain a lot of auxiliary circuits to compute the next address it will go to[1]. Regardless of all that, the fetching logic is the blob of circuits responsible for "Walking over the RAM" and forwarding each value it finds to the rest of the processor.
Now fetching is out of the way, we need to execute the instruction we are pumping out of the RAM. Before we execute, however, we need to "Decode". Decoding is probably what's your original question is about. Instructions stored in the RAM do not contain all the information necessary to actually carry out all operations they describe. For example an instruction might "say" (in encoded form off course) : Add 2 to register A and store the result in register B. You might think that's all perfectly specific, but that sentence is in fact several steps long : First make the ALU take Register A as a first operand[2], then generate the constant 2 and make it the second operand of the the ALU, then generate the bit pattern that tells the ALU to add, finally unlock the "LOAD" bit for Register B which tells it to accept the result coming out of the ALU and overwrite it's current value with it. Modern instruction sets get pretty complex extremely fast, if you store the myriad explicit steps in each instruction you might wind up with an instruction encoding that takes maybe a thousand bit per instruction. So you instead make each instruction a compressed form of the operations it entail, and design the "Decoding" circuits that take each instruction and "understands" it ; by which I mean it makes a lot of "low level" decisions about each section of the instruction.
So to answer to your question, the ADD command doesn't tell the whole system anything. It is thrown out of the RAM by the fetcher at the decoder, the decoder has a lot of circuits (mostly Multiplexers and look-up tables) that looks at each small part of the instruction and generate a lot of control signals that tells each part in the execution backend[3] what to do in minute details to actually carry out the operations that the instruction described. Those control signals are probably what you mean, they are generated by the decoder and tell all the circuits downstream of the decoder what the heck that instruction "means"(i.e. what should each one do in response to it).
Resources:
Here is a brilliant game that walks you through the process of making a simple 16 bit processor from nothing but a Nand gate : http://nandgame.com/
The game is based on the first four chapter of : https://www.nand2tetris.org/course
A project-based course/book that walks you through all the steps necessary to create a fully functioning computer (complete with an OS and a programming language) from nothing but Nand gates.
The name of the field you might be interested in to know how computer fake "Understanding" from nothing but a bunch of silicone and electricity is called "Computer Architecture", google "Books similar to Nand To Tetris" to find books that presents the whole journey in larger details.
Asides:
[1] The next address might even be something totally unrelated to the current address. For example, an instruction in a program that computes whether X > Y and do something different accordingly might say "Subtract Y from X and jump five lines of code ahead if the result was greater than zero". That "Jump" is just a directive to the fetching logic to fetch the next instruction from an entirely different location in RAM, other than the normal location to do which is the one next to the current. Without that ability to "Control Flow" (direct the execution of the program according to the results computed), Computers are literally a stripped-down version of themselves that only executes a linear list of instruction to completion and nothing more.
[2] A multiplexer (and it's close cousin : a demultiplexer) is the basic "Choice primitive" in Logic circuits, it takes n inputs and outputs one of them depending on the result of the "Selection bits". For example, the simplest multiplexers take 2 input and a one selection bit, it outputs the first input if the selection was zero, else it outputs the second input. The ALU of the computer is connected to all possible operands it might take (Register, constants, etc..) through a huge multiplexer, the Decoder is responsible for generating the signal which tells the multiplexer which operand to forward to the ALU, and it does that based on the instruction given.
[3] Processors conceptually separate the parts of the processor responsible for "Interpreting an instruction" (The fetcher and the decoder) from the parts that actually executes what it says. It calls the first chunk the "Frontend" and the second one the "Backend".
2
u/BakedFilosofer Nov 14 '20
I think I got it with this one ! Really appreciate the effort, have a great day fellow redditor
1
u/MirrorLake Nov 14 '20 edited Nov 14 '20
how does the operation code for ADD tell the whole system to take take the data out of the RAM and put it into the 8-bit adder.
It doesn't. The ADD opcode essentially just selects the adder (circuit that adds two registers).
That means that it was the programmer's job on a previous line of code to ensure that both register1 and register2 hold the appropriate data that needs to be added!
More detail:
The opcode is provided as input into a demultiplexer circuit, interactive example here. See p. 197 in your book for a similar circuit, for people without the book it looks like this.
Example 1 - (the '1' on the left side is just an 'on' switch).
So say as designers, we want the binary input of 011 to be our opcode for ADD. Whenever the input lines receive 011, like in my example 1 photo, ONLY the '3' line receives current out. Somewhere beyond the Ex1 photo, that '3' line flows to the 'on' input line of our hypothetical adder circuit, and the adder does the work of adding two numbers together that the programmer had already placed into registers.
3
u/Odys Nov 14 '20
I design electronic equipment using analog circuits and controllers; but when I read some schoolbooks I don't seen to have a clue... The code flips the voltage on a pin or reads the voltage on a pin.
1
u/BakedFilosofer Nov 14 '20
Yeah that's what I imagine to happen but, wouldn't that need a while new chung of circuitry to "translate" the commands?
1
u/Odys Nov 14 '20
Often switches can be connected directly to an input. Some controllers have inputs you can program to switch an internal resistor to positive, so the input will always read 1 until someone operates the switch and shorts the internal resistor to ground. Displays often don't need any extra circuitry. Analog circuits you do usually need when you need to read an analog voltage, as it's rare that the input will work fine in the range you need. Usually this will be some kind of amplification using opamps, with some protective circuitry to keep the voltage within limits at all times if signals come from outside the "box".
1
2
u/jeffbell Nov 14 '20
This diagram is not a typical processor. It has a separate data and code memory (Harvard style) and seems to be just a portion of the design.
What does the caption say?
1
u/BakedFilosofer Nov 14 '20
Indeed it's not a cpu, but rather a simple adder which the book later evolves into an 8bit cpu but it didn't really explain how the actual code, instructs the computer to do stuff.
2
u/corank Nov 14 '20
There are many different ways to implement that in hardware and the implementation itself is called the microarchitecture. The microarchitecture of a modern CPU is usually very complex with all kinds of optimisation tricks to improve the performance. Let me start from the simplest microarchitecture and talk about some most common optimisations one by one.
Simplest: you have a register called the program counter (pc) which points to the address of the instruction to execute. The address is input to a instruction fetcher that loads the instruction. The instruction is basically bytes and needs to be recognised by a decoder. At this stage what operation this instruction is and what gpr (general purpose registers) or memory address are known. Then you basically do the work accordingly: do some arithmetic in ALU, load/store data at an address, write some result to a register and decide the next pc. Everything can be put in one single clock cycle.
Pipeline: if everything is placed in one cycle, all the operations for an instruction are executed sequentially, and this causes waste of resources. When you are adding two values in ALU for example, your decoder and instruction fetcher among other components are basically sitting there idly. So most CPUs are pipelined and work like pipelines in a factory: instruction fetcher always fetches, decoder always decodes, and at the end of each cycle everyone finishes its own work and hands the result to the next guy. There’re some tedious details that need to be handled with care. For example, what if a later instruction requires the result of an earlier instruction that’s still in the pipeline. How to decide pc when the previous instruction is branch but is not finished yet, etc.
Speculative execution: when the previous branch instruction is executing, the CPU can guess the next pc. The guess might be wrong and if that’s the case the wrong instruction needs to be cleared out from the pipeline, wasting a few cycles. A sophisticated branch predictor based on knowledge of common program constructs (e.g. loops) or data it collects during runtime (e.g. the previous resolution of this branch) can be used to improve the accuracy of the guess and hence improve the performance.
Out of order execution: sometimes your pipeline needs to wait because some data is not available. For example we have three instructions a b c. A loads some data from memory to a register and b needs to use this register. Then b would need to wait until the data is loaded. But why should c wait if it’s going to do something irrelevant? In this case c could proceed even though its previous instruction b is waiting for dependency to be resolved. The actual execution inside the cpu then could be made out of order to improve the performance.
2
2
u/AdOk5119 Dec 02 '20
I found this post because I had the same question! I still haven't been able to find the answer... I want to know at the most basic level (like how the gate voltage of a single mosfet is generated from code... how was the first code even implemented without a monitor and keyboard!) Haha it's absolutely mind fucking to me how type characters actually cause a voltage to appear.
31
u/abw Nov 14 '20
I highly recommend you check out Ben Eater's Build an 8-bit computer from scratch series.
It's a great way to really understand the how machine code and hardware interact.