Salta al contenuto
Note per Studenti Programming Fundamentals Report

Programming Fundamentals

In questa pagina 4

This note follows the path from the machine to high-level languages: machine code, assembly language, high-level languages, compilers and interpreters, and the trade-off between portability and efficiency. It continues Computer ArchitectureModern computers follow the von Neumann model: a CPU (ALU, control unit, registers, cache) driven by a clock runs a fetch-decode-execute cycle on programs and data stored in the same memory; memory is a hierarchy from fast, small and volatile (registers, cache, RAM) to slow, large and persistent (SSD, disk, tape); CPU, memory and I/O talk through a bus made of data, address and control lines on the motherboard.Computer Architecture → (CPU, memory, program counter) and the notion of program from Introduction to Computer ScienceComputer science is about problems, algorithms and computation, not about machines; the Turing machine fixed what is computable, complexity classes say what is feasible, a program is a sequence of simple operations and decisions, and an algorithm is a finite, executable method that always terminates (examples: doubling an investment, Sieve of Eratosthenes, divide and conquer, plus the Traveling Salesman and Halting problems).Introduction to Computer Science →. Bits and integer encodings are treated in Representation of InformationEverything in a computer is a sequence of bits, so each kind of information needs a coding. Natural numbers use positional notation in base 2 (conversion by repeated division by 2); signed integers use two's complement (range from minus 2 to the n minus 1 up to 2 to the n minus 1, minus 1), where negation is invert-all-bits-and-add-1, sums are plain binary sums and overflow is detected on the two top carries; hexadecimal groups bits in fours; fractions use fixed point or IEEE 754 floating point (sign, exponent in excess 127, 23-bit fraction) and are only approximate; characters are unsigned integers in a code table (ASCII, Unicode); images, video and sound are stored as numbers too (pixels, frame differences, samples).Representation of Information →.

1. Machine code

  • The elementary instructions a CPU can execute are called machine instructions.
  • Machine code is the sequence of machine instructions that make up a program.
  • The set of machine instructions, the instruction set, is specific to a particular CPU: that of the x86 processor family differs from that of the Arm family.
  • One particular CPU is the Java Virtual Machine (JVM). It is not a real CPU but, for the moment, it can be considered as one.
  • The CPU is an interpreter (executor) of the set of machine instructions of the CPU itself: it can execute the instructions defined in its own instruction set.

Encoding of machine instructions

Machine instructions are encoded as bit configurations (opcodes) stored in memory. Opcodes can be interpreted as integers. Examples for the JVM:

Meaning Instruction code (bits) Encoding
load the value in the memory cell with address 40 into a register 00010101 00101000 (op 21, addr 40) 21 40
write value 100 into another register 00010000 01100100 (op 16, value 100) 16 100
if the first value is greater than the second, continue with the instruction in memory location 240, otherwise with the one following the current 10100011 11110000 (op 163, addr 240) 163 240

The three instructions together become the integer sequence 21 40 16 100 163 240. (The slide notes that how to convert bit sequences to integers is not yet known at this point; see Representation of InformationEverything in a computer is a sequence of bits, so each kind of information needs a coding. Natural numbers use positional notation in base 2 (conversion by repeated division by 2); signed integers use two's complement (range from minus 2 to the n minus 1 up to 2 to the n minus 1, minus 1), where negation is invert-all-bits-and-add-1, sums are plain binary sums and overflow is detected on the two top carries; hexadecimal groups bits in fours; fractions use fixed point or IEEE 754 floating point (sign, exponent in excess 127, 23-bit fraction) and are only approximate; characters are unsigned integers in a code table (ASCII, Unicode); images, video and sound are stored as numbers too (pixels, frame differences, samples).Representation of Information →. It also shows a MIPS32 "add immediate" instruction split into opcode, two register fields and an immediate value.)

Categories of machine instructions

In all CPUs the machine instructions fall into these categories (instruction names are examples only):

Category Description Examples
Data transfer between registers and main memory LOAD (towards a register), STORE (towards the memory)
Arithmetic and logical operations performed by the ALU; arithmetic gives a number, logic gives false or true ADD, SUB, MUL, DIV; AND, OR, NOT
Jumps alter the sequential execution flow (modify the Program Counter) unconditional JUMP; conditional JZ (jump if a value is zero), JGZ (jump if greater than zero)

2. Assembly languages

Layers shown on the slides (bottom to top): hardware, machine language, assembly language, high-level language (Java, C++, Pascal, FORTRAN, C, ...), object-oriented and visual languages. Machine and assembly language are "low level", the rest "high level".

Why assembly

To run a program, the bit patterns of its machine instructions must be written into central memory, so one would need to know all the numerical codes (like 21 40 16 100 163 240). This long and tedious operation, done manually by programmers in the early days, was soon automated by a program running on the computer itself: the assembler. (The slide also shows the inverse tool, the disassembler.)

With assembly language the programmer writes mnemonics (abbreviated names) for machine instructions, much easier to remember than opcodes. The previous JVM example:

iload     40
bipush    100
if_icmpgt 240

The assembler translates this into machine instructions using the opcode table:

Assembly instruction Opcode
iload 21
bipush 16
if_icmpgt 163

Result: 21 40, 16 100, 163 240. Languages with mnemonic codes are called assembly languages, one for each CPU.

Symbolic names

The assembler can also assign names to memory addresses and numerical values and use them in instructions:

iload     rate
bipush    maxRate
if_icmpgt tooMuch

with symbolic names rate = 40, maxRate = 100, tooMuch = 240. The program becomes much more readable because it highlights the meaning of addresses and values.

In assembly language there is a one-to-one correspondence between the assembly instruction set and the processor instruction set.

Assembler workflow

The assembler is a program that takes as input a file with assembly source code and produces a file with the executable code (machine instructions). For now, a file is a collection of data stored in secondary memory and identified by a name.

Steps: write the whole assembly program in a file -> translate it into machine code (executable file) with the assembler -> run the executable file.

Advantages and problems

  • Advantage: assembly is a big step forward compared with programming in machine language.
  • Problem: many instructions are needed even for the simplest operations.
  • Problem: each CPU has its own assembly language, so the instruction sequence of the same program changes with the CPU. Writing programs that run on different CPUs is very expensive, because basically they must be completely rewritten.

3. High-level programming languages

Timeline from the slides:

Period Development Languages
1950s first high-level languages FORTRAN (first "real" language), BASIC, COBOL
1960s-1970s structured programming Pascal (Niklaus Wirth, 1968), C (Brian Kernighan and Dennis Ritchie, 1970-75)
1980s-1990s object-oriented programming C++ (Bjarne Stroustrup, 1979), Java (James Gosling and Patrick Naughton, 1991), Python (Guido van Rossum, 1991)

In a high-level language the programmer expresses the sequence of operations without going down to the detailed level of assembly or machine instructions. The same program at the three levels (slide):

  • machine code: 21 40 16 100 163 240
  • assembly code: iload rate, bipush maxRate, if_icmpgt tooMuch
  • Java code:
java
if (rate > maxRate)
    System.out.print("too much");

Syntax

There are many high-level languages, just as there are many human languages. The same instruction in Java and in Pascal:

java
if (rate > 100) System.out.print("Too much");
if rate > 100 then write ('Too much');

The designers of a language choose its syntax as a compromise between readability, ease of compilation and consistency with other languages.

Programming languages, being created by people, have a much more rigid syntax than natural languages, to help the compiler. The compiler reports syntax errors but does not try to guess, as a human would, because that would make its insights hard to verify: this gives better error reporting. Example on the slide: if (rate > 100)) System.out.print("Too much"); has one bracket in excess.

Compiler

A compiler reads a high-level program and generates the corresponding program in the machine language of a specific CPU.

  • High-level languages are independent of the CPU, but the compiled product (executable code) is CPU specific: the program must be compiled with a different compiler for each CPU type on which it has to run.
  • Source code is code written in a programming language; code in machine language is executable code.
  • The compiler takes as input a file of high-level code and outputs a file of executable code for one CPU. The same source can give executable code for different processors using different compilers (compiler A for type A CPU, compiler B for type B CPU).

Workflow of a compiled language: source code + libraries -> compiler (loader) -> executable file -> program in execution.

Interpreted languages

  • The first commercial high-level languages, such as FORTRAN, were mainly implemented with compilers that translated the source into machine code before execution.
  • Soon an alternative emerged: instead of translating the whole program beforehand, an interpreter executes a program by processing its source code (or an intermediate representation) at run time. Languages associated with this approach are called interpreted languages. Lisp (1958) was one of the earliest high-level languages widely associated with interpreted execution.

Workflow of an interpreted language: source code + libraries -> interpreter -> program in execution.

Python is an interpreted language. Users can write and execute code interactively, one statement at a time, or run complete programs stored in files. Example on the slide, from the interactive prompt:

python
>>> 3+5
8

4. Portability and efficiency

Whether a language is compiled or interpreted strongly affects:

  • portability: how easily the same source code runs on computers with different CPUs and operating systems;
  • efficiency: how fast a program executes.

Both matter when choosing a language for a project.

Interpreted language Compiled language
Portability generally portable at the source code level, provided a compatible interpreter exists on the target platform portable at the source code level, but must be recompiled for each target CPU and operating system; generally not portable at the executable level (the executable has machine code for a specific CPU architecture and often a specific operating system)
Efficiency generally less efficient: part or all of the translation from source to machine instructions is done during execution generally more efficient: translation is done before execution and the executable runs directly on the target CPU
Good choice when portability is the primary concern execution efficiency is the primary concern

Summary: if you need only portability, interpreted languages are the best choice; if you need only efficiency, compiled languages; if you want both, as almost always happens, Java can be the winning choice.

Versione ripasso

Levels of language (low to high): hardware, machine language, assembly language, high-level languages (Java, C++, Pascal, FORTRAN, C, ...).

Machine code.

  • A machine instruction is an elementary operation the CPU executes; the set of them is the instruction set, specific to each CPU (x86 differs from Arm).
  • Instructions are encoded as bit patterns (opcodes), readable as integers. JVM example: 21 40 (load address 40), 16 100 (write 100), 163 240 (if greater, jump to 240).
  • Categories: data transfer (LOAD, STORE), arithmetic and logic (ADD, SUB, MUL, DIV; AND, OR, NOT), jumps (JUMP, JZ, JGZ), which modify the program counter.

Assembly.

  • An assembler translates mnemonics (iload, bipush, if_icmpgt) into opcodes and turns symbolic names into addresses and values.
  • One assembly language per CPU; there is a one-to-one correspondence with its instruction set.
  • Advantage: more readable than machine code. Problems: many instructions are needed, and programs must be rewritten for every CPU.

High-level languages. The programmer describes the steps without the detail of machine instructions. Syntax is rigid on purpose: the compiler reports errors and does not guess the intent.

Compiler vs interpreter.

  • A compiled languagea language whose programs are translated into executable code before execution: source code plus libraries goes through the compiler, giving an executable file for one CPU. Source is CPU independent, executable code is not.
  • An interpreted languagea language whose programs are executed by an interpreter that processes the source code or an intermediate representation at run time: an interpreter runs the source at run time. Python is interpreted; Java is primarily compiled.

Portability vs efficiency.

Aspect Interpreted Compiled
Portability good at source level, needs an interpreter on the target source portable, executable must be recompiled per CPU and OS
Efficiency lower, translation happens during execution higher, executable runs directly on the CPU

If you need only portability, choose interpreted; only efficiency, compiled; both, Java.

Common mistakes: assuming a high-level program runs unchanged on any CPU once compiled; assuming source portability means executable portability; expecting the compiler to guess a missing bracket (in if (rate > 100)) it reports the extra bracket as an error).

Teoria collegata