Machineboy空
[From Nand to Tetris] 모듈 5. Machine Language 본문
컴퓨터가 어떤 일을 해야하는지에 관한 것을 적은 기계어를 디자인하는 일은 굉장히 중요!
a taste of low-level programming을 제공할 것
Keyword
- op codes
- mnemonics
- binary machine language
- symbolic machine language
- assembly
- low-level arithmetic
- logical
- addressing
- branching
- I/O commands
- CPU emulation
- low-level programming
4.1 Machine Languages : Overview
ALU도 만들고 메모리 계층도 만들었다. 그걸 조립해 컴퓨터를 바로 만들 수 있지만 살짝 미뤄두고,
우리가 컴퓨터로 무얼할지에 대해 먼저 생각해 보겠다.
게임도 할 수 있고 글도 쓸 수 있고, 근데 단 하나의 기계로 어떻게 이렇게 많은 일을 할 수 있는거지?
How is possible that we can do all these different things with a single hardware, with a single machine?




hardware perform many things according to the program
the program had a sequence of instructions
how to specify the instructions
how do we know which instruction to perform at any given stage and time?
add two number한다면
- how exactly
- where exactly will it get two values
- where should it put the result

기계어는 terrible
인간친화적으로 만든 게 high level language
automatic programs called compilers which translate that into the machine language, into the software, which actually tells the hardware what to do when it runs it
우리가 기계어를 알아야 하는 이유
machine language로 직접 프로그래밍 하진 않지만,
실제 구동하는 하드웨어와 그 위에 작동하는 소프트웨어를 다룰 것이기 때문에 이해하는 것이 좋아요


Assembler : 어셈블리 언어로 작성한 후, 2진수로 변환하면 어떨까?



4.2 Machine Languages : Elements
모든 기계어에서 등장하는 basic elements에 관해
- 하드웨어/소프트웨어 인터페이스에 관한 스펙
- 하드웨어 아키텍쳐와 대응
- trade-off에 대한 고민
기계의 작동
- 연산, 논리 연산, 다양한 데이터 타입 제공
기기 스펙에 따라 속도도 다르고 연산이 가능한 범위도 다름


메모리에 접근하는 것은 expensive operation
- Address : large memory 라면 구체적으로 어느 구역(adress)에 접근할 지 정하는 것이 에너지가 많이 소모된다.
- 예) 두 숫자를 더하라! -> 두 수의 large addressess
- Value: CPU 스피드에 비해, 값에 접근하는 속도가 느리며 waste
without requiring all these costs of specifying the large address and getting the information from a far away place if you wish
Solution: Memory Hierarchy


Arithmetic unit(산술장치)로 부터 멀어질 수록, 메모리가 커진다.
그래서 접근하기가 어려워 진다.(주소가 길어지기 때문에, 값을 받아오는데 오래 걸리기 때문에)
메모리 계층의 다양한 수준(level) 은 각각 다른 방식으로 관리됩니다.
그러나 지금 우리가 논의하려는 것은 레지스터(Register), 즉 가장 작고, 보통 CPU 내부에 직접 위치하는 메모리에 대한 것이다.
Register에 관해
CPU 안에 위치. 그래서 값에 접근하고 불러오는데 거의 delay가 없음
그들의 역할과 타입은 기계어로 작성
- Memory location register : 데이터 저장
- 예) 레지스터 1과 레지스터 2의 값을 더하라
- use them as address
- 예) 레지스터 1의 값을 A라는 레지스터가 지정한 메모리 주소에 저장하라



기계어에서 입출력을 어떻게 처리하는지
입출력 장치들(프린터, 화면, 센서, 키볻, 마우스 등)에 접근하는 방법 = 이 장치들을 제어하는 레지스터를 메모리의 일부로 연결
예) 마우스를 움직일 때마다, 그 움직임의 정보가 어떤 레지스터에 기록
운영 체제의 드라이버 일부로 입출력 장치가 연결된 주소를 정확히 알아야 하고, 이 장치와 어떻게 통신하는지도 알아야 하며, 그 주소에 저장된 값들이 실제로 무엇을 의미하는지도 이해해야 한다.

Flow Control : 다음에 어떤 명령어를 실행할지
- 소프트웨어가 하드웨어에게 작업을 다시 수행하거나 돌아가거나 다른 위치로 점프하라고 지시할 수 있는 기능.
- Conditional jump



4.3 The Hack Computer and Machine Language
overview of the hardware platform on which the machine language is going to operate
컴퓨터의 세가지 메인 요소
16 bit 컴퓨터로 가정.
16bit chunk로 구성되어 있기 때문에,
뭔가 저장,검색, 이동하려고 하면 16비트를 함께 저장,검색, 이동해야 한다.

- data memory : value is going to be stored in a memory register
- CPU : a device which is capable of manipulating 16 bit value using mostly the ALU which resides inside the CPU
- instruction memory : seperate memory space
- Buses
컴퓨터를 컨트롤하는 소프트웨어
software consists of machine language

Control & Reset Button
컨트롤을 이야기하려면 리셋 버튼을 알아야 한다.


User 관점에서의 control 프로세스
1) program이라는 software를 작성한다.
2) ROM에 넣는다. (read only memory)
3) Reset버튼을 누른다.
4) program이 실행된다.
컴퓨터가 어떻게 작동할지는 전적으로 program의 내용을 따른다.
Register

- D register : 16bit 값 저장, 데이터 한 조각
- A register : 16 bit 값 저장, 데이터 값 또는 주소
- M register : selected memory register , 선택된 레지스터
A-instruction(address) & C-instruction
레지스터를 다루는 지시들.







4.4 Hack Language Specification
Overview
CPU, RAM, ROM으로 이루어진 하드웨어 플랫폼이 있고,
A-명령과 C-명령으로 이루어진 기계어가 있다.

기계어를 symbolic하게 쓰는 방법, 즉 사람이 이해하기 쉽게 쓰고,
이것을 기계가 이해하는 binary 언어로 변환하는 것이 assembler의 역할

명령어 종류 별 binary syntax 맵핑








HackProgram 예시


4.5 Input / Output
컴퓨터 기본 구조를 확장해, 이제 입출력 장치까지 붙여보자!
peripheral : 주변의
주변 장치라고 불린다.


고차원적으로는 소프트웨어 라이브러리 등을 써서 제어를 하겠지만, 저수준에서는 그저 bit일 뿐
Output (Screen)
output을 manipulate하는 데 가장 중요한 것은 screen memory map
RAM안 에 지정된 영역.
스크린은 연속적으로 memory map의 요소를 refresh한다.

Hello World를 출력하기 위해서는 아주 구체적인 위치에 있는 픽셀들을 켜고 끄는 작업을 해야 합니다.

어떤 비트가 어떤 픽셀에 대응하는지 정확히 설명하는 매핑해야 한다.
bit는 1차원이고 픽셀은 2차원인데 어떻게 하지?
우선, 우리가 메모리에 접근할 때, 한 번에 16비트만 가져올 수 있다.
개별 비트에 접근할 수 없다.






값을 읽고, 쓰고 하는 것은 RAM의 기본적인 기능임!
Input (Keyboard)
키보드 메모리맵은 single register, 16 bit register



16bit만 있으면 다른 다양한 언어, 숫자 등을 나타낼 수 있다.

4.6 Hack Programming, Part 1 - Working with Memory and Register
over view of two instructions (A 명령, C 명령)

translate symbolic program to binary code 하는 방법
- Assembly
- supplied CPU Emulator


Low-level programming에 대해서 이야기할 때 나오는 주제들.
다른 언어들과 동일함.

메모리와 레지스터는 빵과 버터처럼 짝꿍!

A 레지스터의 좋은 부작용 : A레지스터에 값을 넣으면 그 값에 해당하는 주소를 가진 레지스터가 M레지스터로 선택됌
- 예제들


만약 해커가 밑에 설치한 잠재되어있는 악성 프로그램(NOP, Null instructions or Null Opcodes)이 실행되기 전에 종료하려면?


알아야 할 것은 컴퓨터는 한시도 쉬지 않는다는 것이다.
we can end the program with an infinte loop


4.7 Hack Programming, Part 2 - Branching, Variable, Iteration
1️⃣ Branching
- computer to evaluate a certain boolean condition, : 참, 거짓 조건을 평가
- based on this value to decide whether, or not we want to jump, : jump할지 말지 정하고
- execute next instruction : 다음 명령 실행
ex) if-else 문, switch 문, while 문 등
Machine Language에서는 딱 하나의 branching을 제공해.


아직까지 readable하지 않은 코드들.. 어떻게 하면 더 가독성이 좋아질까
go to 8을 이제 @LABEL로 바꿔보자.
이러한 레이블을 구체적인 숫자로 바꾸는 일은 assembler와 translator의 역할이다.


2️⃣ Variable
- an obstruction of a container that has a name and a value. : 이름과 값을 가진 컨테이너의 추상화
고급 언어에서는 다양한 데이터 타입(정수형, 실수형, 문자열 등)과 변수 타입이 있지만,
기계어에서는 하나의 변수 타입(16비트)이 존재한다.
- implemented by using single register
하나의 레지스터를 변수, 즉 컨테이너로 활용한다.



branching은 @LABEL형식으로 표기되지만 variable는 그렇지 않다.
3️⃣ Iteration
1+2+3+ ...+ n을 수행한다고 해보자!



4.8 Hack Programming, Part 3 - Pointers, Input/Output
1️⃣ Pointers
배열을 선언했다고 치자.
- machine language no longer recognizes the array obstruction : 기계어는 배열 구조를 인식하지 못한다.
- know the base address of this segment and the length of the array that programmer has decided to declare: 메모리의 시작 주소와, 배열의 길이만 알 뿐이다.
ex) 100번 위치에서 시작해서 10개의 항목에 대해 무언가 수행하라.
- variables that store memory addresses are called pointer. : 메모리 주소를 담는 변수





2️⃣ Input / Output
how pointer manipulation comes to play in the when we write code that interacts with the screen and other similar peripheral devices.
다른 입출력 장치들과 상호작용할 때, pointer가 어떻게 조종하는 가

Drawing Rectangle하는 방식



programmer cannot manipulate the physical screen directly.
But what we can do is manipulate the screen memory map.


low-level language를 작성하는 것은 매우 번거롭다.
that's why we normally do it in a high-level language and then, after we compile it into machine language, we get the desired effect.
그래서 우리는 고차원 언어를 쓰고 그걸 기계어로 컴파일해서 원하는 동작을 수행하려고 하지.
근데 Hack language는 two command only만 가지고 있고,
그것은 ability to represent symbols 만 할 수 있다.
이 단순한 기능을 통해 우리는 can execute any program that comes to our mind.
4.9 Project 4 Overview


4.10 Perspectvies
여기서 쓴 기계어와 실제 기계어가 약간다를 수 있다만 원리 같음
'Computer > CS' 카테고리의 다른 글
Exercism - Strain: 제너릭 메소드, 델리게이트, yield return (0) | 2025.02.13 |
---|---|
[From Nand to Tetris] Project 3 : Bit, Register, RAM8, RAM64, RAM512, RAM4K, RAM16K, PC (0) | 2025.02.04 |
[From Nand to Tetris] 모듈 3. Memory (0) | 2025.02.03 |
[From Nand to Tetris] Project 2 - HalfAdder, FullAdder, Add16, Inc16, ALU (0) | 2025.01.23 |
[From Nand to Tetris] 모듈 2.Boolean Arithmetic and the ALU (0) | 2025.01.22 |