Skip to main content

06 - Semantic Analysis, Code Generation, Optimization

Check the types, translate to three-address code and optimize without changing the output, testing on 5,000 programs that nothing changes, errors included.

What do you think about this article?

06 - Semantic Analysis, Code Generation, Optimization
Formal Languages & Compilersfedericocalo.dev

At a Glance

Check the types, translate to three-address code and optimize without changing the output, testing on 5,000 programs that nothing changes, errors included.

The parser has handed you a tree. Now you have to turn it into a program that runs, and if possible runs faster, without changing a comma of what it prints. The compiler does three things, in this order: it checks that the program makes sense (variables declared, types consistent), it translates it into a flat intermediate representation, and it optimizes it with transformations that preserve behavior. In this article you build them for a minimal language of let and print, and above all you test them: the same program, run by three independent routes, must give the same output, errors included.

The parser is the recursive descent one of article 4, with one difference that I had postponed there: the right-recursive nonterminals (E', T') become loops that accumulate on the left, so 10 - 3 - 2 is 5 and not 9. Python 3.14, no external libraries; the three listings were run twice with the same output on 2026-11-13.

The language, the lexer and the parser

The language has two types, int and bool, two statements, let name = expression; and print expression;, and the operators + - * /, unary minus, < and ==. It has no jumps, loops or functions: it is a choice whose cost I state at the end. The grammar, in EBNF form, is in the docstring of the first listing: five levels of precedence, from comparison (the weakest) to the literal or the parenthesis (the strongest). Each level is a function of the parser, and the repetition braces { ... } are the whiles.

In the listing, token uses a regular expression to split the source, as in the first two articles of the series: numbers, identifiers and operators; keywords are identifiers recognized by name. The Parser class has one method per nonterminal. In somma and prodotto the while loop builds (op, a, b) with a absorbing the previous result: that is left associativity. Comparison, instead, is an if and not a loop, so 1 < 2 == true is not a sentence of the language: it is rejected, and that is a grammar decision, not a parser error.

Semantic analysis lives in controlla. It builds the symbol table, a dictionary from name to type, and visits every expression computing its type. Here the grammar is not enough: print b; is syntactically perfect, but b does not exist, and a context-free grammar has no way of remembering which names have been introduced. That is why the check is a separate step, working on the tree. Note the order in let: the type of the right-hand side is computed first and then the name is inserted, otherwise let x = x; would be valid.

"""Lexer, recursive descent parser and semantic analysis of a minimal language.

    programma   -> istruzione*
    istruzione  -> "let" ID "=" espr ";"  |  "print" espr ";"
    espr        -> somma [ ("<" | "==") somma ]
    somma       -> prodotto { ("+" | "-") prodotto }
    prodotto    -> unario { ("*" | "/") unario }
    unario      -> "-" unario | primario
    primario    -> NUM | ID | "true" | "false" | "(" espr ")"
"""
import re


class ParseError(Exception):
    pass


class SemanticError(Exception):
    pass


TOKEN = re.compile(r"\s*(?:(\d+)|([A-Za-z_]\w*)|(==|[-+*/<()=;]))")
PAROLE = {"let", "print", "true", "false"}


def token(src):
    """Returns (type, value) pairs; keywords and operators have type = text."""
    out, pos, src = [], 0, src.rstrip()
    while pos < len(src):
        m = TOKEN.match(src, pos)
        if not m:
            raise ParseError(f"unexpected character {src[pos:].lstrip()[0]!r}")
        num, ident, op = m.groups()
        pos = m.end()
        if num:
            out.append(("num", int(num)))
        elif ident:
            out.append((ident, ident) if ident in PAROLE else ("id", ident))
        else:
            out.append((op, op))
    return out + [("end", None)]


class Parser:
    def __init__(self, tokens):
        self.t, self.i = tokens, 0

    def tipo(self):
        return self.t[self.i][0]

    def mangia(self, atteso):
        if self.tipo() != atteso:
            raise ParseError(f"expected {atteso!r}, found {self.tipo()!r}")
        valore = self.t[self.i][1]
        self.i += 1
        return valore

    def programma(self):
        istruzioni = []
        while self.tipo() != "end":
            istruzioni.append(self.istruzione())
        return istruzioni

    def istruzione(self):
        if self.tipo() == "let":
            self.mangia("let")
            nome = self.mangia("id")
            self.mangia("=")
            e = self.espr()
            self.mangia(";")
            return ("let", nome, e)
        if self.tipo() == "print":
            self.mangia("print")
            e = self.espr()
            self.mangia(";")
            return ("print", e)
        raise ParseError(f"expected 'let' or 'print', found {self.tipo()!r}")

    def espr(self):
        a = self.somma()
        if self.tipo() in ("<", "=="):
            op = self.mangia(self.tipo())
            a = (op, a, self.somma())
        return a

    def somma(self):
        a = self.prodotto()
        while self.tipo() in ("+", "-"):             # the loop accumulates on the left: (a - b) - c
            op = self.mangia(self.tipo())
            a = (op, a, self.prodotto())
        return a

    def prodotto(self):
        a = self.unario()
        while self.tipo() in ("*", "/"):
            op = self.mangia(self.tipo())
            a = (op, a, self.unario())
        return a

    def unario(self):
        if self.tipo() == "-":
            self.mangia("-")
            return ("neg", self.unario())
        return self.primario()

    def primario(self):
        k = self.tipo()
        if k == "num":
            return ("num", self.mangia("num"))
        if k == "id":
            return ("var", self.mangia("id"))
        if k in ("true", "false"):
            self.mangia(k)
            return ("bool", k == "true")
        if k == "(":
            self.mangia("(")
            e = self.espr()
            self.mangia(")")
            return e
        raise ParseError(f"expected an expression, found {k!r}")


def parse(src):
    p = Parser(token(src))
    programma = p.programma()
    return programma


def controlla(programma):
    """Symbol table and type checking (int or bool). Returns the table name -> type."""
    simboli = {}

    def tipo(e):
        k = e[0]
        if k == "num":
            return "int"
        if k == "bool":
            return "bool"
        if k == "var":
            if e[1] not in simboli:
                raise SemanticError(f"variable {e[1]!r} not declared")
            return simboli[e[1]]
        if k == "neg":
            if tipo(e[1]) != "int":
                raise SemanticError("the minus sign requires an int")
            return "int"
        op, a, b = e
        ta, tb = tipo(a), tipo(b)
        if op in ("+", "-", "*", "/", "<"):
            if (ta, tb) != ("int", "int"):
                raise SemanticError(f"{op!r} requires two ints, found {ta} and {tb}")
            return "bool" if op == "<" else "int"
        if ta != tb:
            raise SemanticError(f"'==' compares different types: {ta} and {tb}")
        return "bool"

    for istr in programma:
        if istr[0] == "let":
            t = tipo(istr[2])                       # right-hand side first: `let x = x;` is not valid
            if istr[1] in simboli:
                raise SemanticError(f"variable {istr[1]!r} already declared")
            simboli[istr[1]] = t
        else:
            tipo(istr[1])
    return simboli


if __name__ == "__main__":
    sorgente = "let x = 10 - 3 - 2;\nprint x * (1 + 2);"
    albero = parse(sorgente)
    print("tree:", albero)
    print("symbols:", controlla(albero))
    sbagliati = ["let a = 1 +;", "let a = 1; let a = 2;", "print b;", "let c = 1 < true;",
                 "let d = -true;", "print 3 $ 4;", "let e = (1 + 2;", "x = 1;"]
    for src in sbagliati:
        try:
            controlla(parse(src))
        except (ParseError, SemanticError) as e:
            print(f"{src!r:26} -> {type(e).__name__}: {e}")

# Output:
# tree: [('let', 'x', ('-', ('-', ('num', 10), ('num', 3)), ('num', 2))), ('print', ('*', ('var', 'x'), ('+', ('num', 1), ('num', 2))))]
# symbols: {'x': 'int'}
# 'let a = 1 +;'             -> ParseError: expected an expression, found ';'
# 'let a = 1; let a = 2;'    -> SemanticError: variable 'a' already declared
# 'print b;'                 -> SemanticError: variable 'b' not declared
# 'let c = 1 < true;'        -> SemanticError: '<' requires two ints, found int and bool
# 'let d = -true;'           -> SemanticError: the minus sign requires an int
# 'print 3 $ 4;'             -> ParseError: unexpected character '$'
# 'let e = (1 + 2;'          -> ParseError: expected ')', found ';'
# 'x = 1;'                   -> ParseError: expected 'let' or 'print', found 'id'

The output has two parts. The first program shows the tree, with 10 - 3 - 2 nested as (10 - 3) - 2, and the symbol table. The second part passes eight wrong programs and reports the type of error: four are semantic errors (name already declared, name not declared, two types that do not combine, minus applied to a boolean) and four are lexical or syntactic. The message says what was found and what was expected, but not the line: this article's lexer does not keep positions, and a real compiler cannot afford to do without them.

Three-address code

The tree is convenient for checking but inconvenient for transforming and executing. The next step flattens it into three-address code: a sequence of instructions, each with at most one operator and three names, %2 = a + 0. The intermediate subexpressions become temporaries %1, %2, where the % character guarantees they do not clash with the user's names: no identifier of the language can begin that way. Every instruction writes one register and reads others: it is a form that is easy to reason about, and in which you can say precisely what depends on what.

One property of the generated program is decisive for everything else: every register is written only once. let cannot be repeated (semantic analysis forbids it) and the temporaries are always new. This is the SSA form, static single assignment: Cytron and others published its efficient computation in 1991 (the title of the article says so; I did not read it in full), and the LLVM language description defines its IR as a representation based on SSA. In our case we do not need the φ functions that SSA requires where two branches rejoin, because there are no branches. With jumps the argument "a name has the same value throughout the program" no longer holds, and the optimizations below have to be rewritten.

In the listing generation is genera, execution is esegui, optimization is ottimizza. Two details deserve attention. The first is dividi: integer division has to be defined by the language, and here it truncates toward zero as in C, because Python's // operator, according to its reference manual, applies the floor function to the mathematical quotient and would give -4 for -7 / 2 instead of -3. The second is puo_fallire: in our language division by zero stops the program with an error, so it is an observable effect, and an instruction that can produce it is not deleted even if its result is not needed.

The transformations are four, and the ottimizza function repeats them until the code no longer changes, because one can reveal work for another:

  • copy and constant propagation: a register that equals another register or a constant is replaced by the value where it is used;
  • constant folding: an operation with two constant operands is computed at once, except x / 0, which stays in order to fail at run time;
  • algebraic identities: x + 0 and x * 1 become x, and x * 0 becomes 0;
  • dead code elimination: a backward pass removes the instructions whose result is not read and that cannot fail.

The first three go forward and the fourth backward, because to know whether a register is needed you have to look at how the code after it uses it. They are not independent: after propagating %1 = 3 - 3 as 0, the division 7 / %1 becomes 7 / 0 and its divisor is a provably null constant. The order of the list matters, and that is why the loop of ottimizza repeats the pair until the fixed point.

"""Three-address code, execution and optimization of a program with no jumps."""
from sintassi import parse, controlla


class ErroreRuntime(Exception):
    pass


# --- generation -----------------------------------------------------------
# Instructions: ("copy", d, x) ("neg", d, x) (op, d, x, y) ("print", x).
# An operand is a register name (str) or a constant (int or bool).
# Temporaries are called %1, %2, ...: an identifier of the language cannot start with %.

def genera(programma):
    ir, contatore = [], [0]

    def nuovo():
        contatore[0] += 1
        return f"%{contatore[0]}"

    def espr(e):
        k = e[0]
        if k in ("num", "bool", "var"):
            return e[1]
        if k == "neg":
            a = espr(e[1])
            d = nuovo()
            ir.append(("neg", d, a))
            return d
        op, a, b = e
        x, y = espr(a), espr(b)
        d = nuovo()
        ir.append((op, d, x, y))
        return d

    for istr in programma:
        if istr[0] == "let":
            ir.append(("copy", istr[1], espr(istr[2])))
        else:
            ir.append(("print", espr(istr[1])))
    return ir


# --- execution ------------------------------------------------------------
def dividi(a, b):
    """Integer division that truncates toward zero, as in C (Python's // rounds down)."""
    if b == 0:
        raise ErroreRuntime("division by zero")
    q = abs(a) // abs(b)
    return q if (a < 0) == (b < 0) else -q


OPERATORI = {"+": lambda a, b: a + b, "-": lambda a, b: a - b, "*": lambda a, b: a * b,
             "/": dividi, "<": lambda a, b: a < b, "==": lambda a, b: a == b}


def formatta(v):
    return ("true" if v else "false") if isinstance(v, bool) else str(v)


def esegui(ir):
    """Returns the printed lines; if division by zero stops the program, the last line says so."""
    registri, uscita = {}, []
    valore = lambda x: registri[x] if isinstance(x, str) else x
    try:
        for ins in ir:
            k = ins[0]
            if k == "copy":
                registri[ins[1]] = valore(ins[2])
            elif k == "neg":
                registri[ins[1]] = -valore(ins[2])
            elif k == "print":
                uscita.append(formatta(valore(ins[1])))
            else:
                registri[ins[1]] = OPERATORI[k](valore(ins[2]), valore(ins[3]))
    except ErroreRuntime as e:
        uscita.append(f"ERROR: {e}")
    return uscita


# --- optimization --------------------------------------------------------
def semplifica(ir):
    """Constant and copy propagation, folding and algebraic identities in a single pass.

    It is valid because every register is written ONCE only: `let` is not repeated and the temporaries
    are new at every use. A definition stays true for the rest of the program.
    """
    noto, out = {}, []

    def sost(x):
        while isinstance(x, str) and x in noto:
            x = noto[x]
        return x

    def intero(x, n):
        return type(x) is int and x == n

    for ins in ir:
        k = ins[0]
        if k == "print":
            out.append(("print", sost(ins[1])))
            continue
        d = ins[1]
        if k == "copy":
            noto[d] = sost(ins[2])
            out.append(("copy", d, noto[d]))
        elif k == "neg":
            a = sost(ins[2])
            if isinstance(a, str):
                out.append(("neg", d, a))
            else:
                noto[d] = -a
                out.append(("copy", d, noto[d]))
        else:
            a, b = sost(ins[2]), sost(ins[3])
            risultato = None
            if not isinstance(a, str) and not isinstance(b, str):
                if not (k == "/" and b == 0):         # a division by zero is not computed: it stays
                    risultato = OPERATORI[k](a, b)
            elif k == "+" and intero(b, 0) or k == "*" and intero(b, 1):
                risultato = a
            elif k in ("+", "*") and (intero(a, 0) and k == "+" or intero(a, 1) and k == "*"):
                risultato = b
            elif k == "*" and (intero(a, 0) or intero(b, 0)):
                risultato = 0
            if risultato is None:
                out.append((k, d, a, b))
            else:
                noto[d] = risultato
                out.append(("copy", d, risultato))
    return out


def puo_fallire(ins):
    """Only division can stop the program, and only if the divisor is not a constant other than 0."""
    return ins[0] == "/" and not (type(ins[3]) is int and ins[3] != 0)


def elimina_codice_morto(ir, divisione_pura=False):
    """Scans backwards: removes the instructions whose result is not needed and that have no effects.

    `divisione_pura=True` is the WRONG version, used in the check: it treats division as pure.
    """
    vivi, out = set(), []
    for ins in reversed(ir):
        if ins[0] == "print":
            usi = [ins[1]]
        else:
            effetto = puo_fallire(ins) and not divisione_pura
            if ins[1] not in vivi and not effetto:
                continue
            usi = ins[2:]
        out.append(ins)
        vivi.update(x for x in usi if isinstance(x, str))
    return out[::-1]


def ottimizza(ir, divisione_pura=False):
    while True:
        nuovo = elimina_codice_morto(semplifica(ir), divisione_pura)
        if nuovo == ir:
            return ir
        ir = nuovo


def mostra(ir):
    righe = []
    for ins in ir:
        k = ins[0]
        if k == "print":
            righe.append(f"print {formatta(ins[1])}")
        elif k == "copy":
            righe.append(f"{ins[1]} = {formatta(ins[2])}")
        elif k == "neg":
            righe.append(f"{ins[1]} = -{formatta(ins[2])}")
        else:
            righe.append(f"{ins[1]} = {formatta(ins[2])} {k} {formatta(ins[3])}")
    return righe


if __name__ == "__main__":
    for titolo, sorgente in (
        ("no errors", "let a = 4 * 5;\nlet b = a + 0;\nlet c = b * 1 - 2 * 9;\n"
                         "let unused = c * c;\nprint c;\nprint c < 3;"),
        ("with a division by zero", "let u = 7 / (3 - 3);\nprint 1;"),
    ):
        programma = parse(sorgente)
        controlla(programma)
        prima = genera(programma)
        dopo = ottimizza(prima)
        print(f"== {titolo}")
        print(f"IR before ({len(prima)} instructions):", *mostra(prima), sep="\n  ")
        print(f"IR after  ({len(dopo)} instructions):", *mostra(dopo), sep="\n  ")
        print("output before:", esegui(prima), " after:", esegui(dopo))

# Output:
# == no errors
# IR before (13 instructions):
#   %1 = 4 * 5
#   a = %1
#   %2 = a + 0
#   b = %2
#   %3 = b * 1
#   %4 = 2 * 9
#   %5 = %3 - %4
#   c = %5
#   %6 = c * c
#   unused = %6
#   print c
#   %7 = c < 3
#   print %7
# IR after  (2 instructions):
#   print 2
#   print true
# output before: ['2', 'true']  after: ['2', 'true']
# == with a division by zero
# IR before (4 instructions):
#   %1 = 3 - 3
#   %2 = 7 / %1
#   u = %2
#   print 1
# IR after  (2 instructions):
#   %2 = 7 / 0
#   print 1
# output before: ['ERROR: division by zero']  after: ['ERROR: division by zero']

Read the two programs in the output. In the first, 13 instructions become 2: c is 20 * 1 - 2 * 9 = 2, everything is computed in advance and the instruction unused = c * c disappears because nobody reads it. In the second, the division by zero is kept: the optimized IR still has %2 = 7 / 0, even though its result is of no use, and indeed the two programs, before and after, end with the same error, without printing the 1. An optimizer that removed that instruction would turn a program that stops into one that prints 1: it would be an incorrect compiler, even with shorter code.

Proving that the optimizer does not change the program

Two examples prove nothing. The verification listing does three things. First: twelve cases chosen by hand for precedence and associativity, with the expected values written by me and one rejected by the grammar (1 < 2 == true). Second: 5,000 random programs, generated with a fixed seed (20261113), where the reference result is computed by the generator itself on its own tree, with Fraction and trunc for division, without going through the parser or dividi. Third: the same check with a faulty optimizer, which treats division as pure, to see whether the check notices.

"""Three-level check: known precedences, random programs with a fixed seed, faulty optimizer."""
import random
from fractions import Fraction
from math import trunc

from sintassi import parse, controlla
from codice import genera, esegui, ottimizza, formatta

SEME, N_PROGRAMMI = 20261113, 5000

# 1. Precedence and associativity: the expected values are those of mathematics and C, written by hand.
ATTESI = [("1 + 2 * 3", "7"), ("10 - 3 - 2", "5"), ("8 / 2 / 2", "2"), ("-2 * 3", "-6"),
          ("7 / -2", "-3"), ("-7 / 2", "-3"), ("2 * (3 + 4)", "14"), ("1 + 2 < 4", "true"),
          ("1 < 2 == true", "REJECTED"), ("2 * 3 == 6", "true"), ("--5", "5"), ("100 / 7 / 2", "7")]


# 2. Program generator with a REFERENCE independent of our parser and our IR.
# A generator tree is ("N", v) | ("V", nome) | ("U", a) | ("B", op, a, b) | ("T"/"F",).
def gen_int(rng, prof, interi):
    if prof == 0 or rng.random() < 0.25:
        return ("V", rng.choice(interi)) if interi and rng.random() < 0.5 else ("N", rng.choice([0, 1, 1, 2, 3, 5, 7, 9]))
    if rng.random() < 0.15:
        return ("U", gen_int(rng, prof - 1, interi))
    return ("B", rng.choice("+-*+-*/"), gen_int(rng, prof - 1, interi), gen_int(rng, prof - 1, interi))


def gen_bool(rng, prof, interi, booleani):
    scelta = rng.random()
    if scelta < 0.15:
        return (rng.choice("TF"),)
    if scelta < 0.25 and booleani:
        return ("V", rng.choice(booleani))
    return ("B", rng.choice(["<", "=="]), gen_int(rng, prof, interi), gen_int(rng, prof, interi))


def testo(a):
    k = a[0]
    return {"N": lambda: str(a[1]), "V": lambda: a[1], "T": lambda: "true", "F": lambda: "false",
            "U": lambda: f"-{testo(a[1])}"}.get(k, lambda: f"({testo(a[2])} {a[1]} {testo(a[3])})")()


def riferimento(a, env):
    """Evaluates with Fraction and trunc: no code in common with dividi() in codice.py."""
    k = a[0]
    if k == "N":
        return a[1]
    if k == "V":
        return env[a[1]]
    if k in "TF":
        return k == "T"
    if k == "U":
        return -riferimento(a[1], env)
    x, y = riferimento(a[2], env), riferimento(a[3], env)
    op = a[1]
    if op == "/":
        return trunc(Fraction(x, y))                    # ZeroDivisionError if y == 0
    return {"+": x + y, "-": x - y, "*": x * y, "<": x < y, "==": x == y}[op]


def programma_casuale(rng):
    righe, atteso, env, interi, booleani = [], [], {}, [], []
    for i in range(rng.randint(3, 8)):
        if rng.random() < 0.6:
            e = gen_int(rng, rng.randint(1, 3), interi) if rng.random() < 0.7 else gen_bool(rng, 2, interi, booleani)
            booleano = e[0] in "TF" or (e[0] == "B" and e[1] in ("<", "==")) or (e[0] == "V" and e[1] in booleani)
            nome = f"v{i}"
            righe.append(f"let {nome} = {testo(e)};")
            atteso.append(("let", nome, e))
            (booleani if booleano else interi).append(nome)
        else:
            e = gen_int(rng, rng.randint(1, 3), interi) if rng.random() < 0.7 else gen_bool(rng, 2, interi, booleani)
            righe.append(f"print {testo(e)};")
            atteso.append(("print", e))
    return "\n".join(righe), atteso


def uscita_attesa(atteso):
    env, uscita = {}, []
    try:
        for istr in atteso:
            if istr[0] == "let":
                env[istr[1]] = riferimento(istr[2], env)
            else:
                uscita.append(formatta(riferimento(istr[1], env)))
    except ZeroDivisionError:
        uscita.append("ERROR: division by zero")
    return uscita


if __name__ == "__main__":
    # 1
    ko = 0
    for src, atteso in ATTESI:
        try:
            programma = parse(f"print {src};")
            controlla(programma)
            ottenuto = esegui(genera(programma))[0]
        except Exception:
            ottenuto = "REJECTED"
        ko += (ottenuto != atteso)
    print(f"precedence, types and syntax: {len(ATTESI)} cases, wrong: {ko}")
    # 2 and 3
    rng = random.Random(SEME)
    tot = errori = prima = dopo = divergenze = divergenze_guasto = 0
    for _ in range(N_PROGRAMMI):
        src, atteso = programma_casuale(rng)
        programma = parse(src)
        controlla(programma)
        ir = genera(programma)
        ott = ottimizza(ir)
        riferimento_uscita = uscita_attesa(atteso)
        tot += 1
        errori += riferimento_uscita[-1:] == ["ERROR: division by zero"]
        prima += len(ir)
        dopo += len(ott)
        divergenze += not (esegui(ir) == esegui(ott) == riferimento_uscita)
        divergenze_guasto += esegui(ottimizza(ir, divisione_pura=True)) != riferimento_uscita
    print(f"programs: {tot}, stopped by a division by zero: {errori}")
    print(f"IR instructions: {prima} before, {dopo} after ({100 * (prima - dopo) / prima:.1f}% fewer)")
    print(f"different output among reference, IR and optimized IR: {divergenze}")
    print(f"with division treated as pure, programs with different output: {divergenze_guasto}")

# Output:
# precedence, types and syntax: 12 cases, wrong: 0
# programs: 5000, stopped by a division by zero: 972
# IR instructions: 95102 before, 13350 after (86.0% fewer)
# different output among reference, IR and optimized IR: 0
# with division treated as pure, programs with different output: 445

The twelve cases have zero errors. Of the 5,000 programs, 972 stop on a division by zero (about one in five, and the share holds for this generator: it depends on how I chose the constants). Among reference, IR and optimized IR there is no different output, errors included, and this is the result that counts. The faulty optimizer, instead, produces a different output in 445 programs: it is not a check that declares everything fine on principle, it notices a defect whose cause I know.

The instructions go from 95,102 to 13,350, 86% fewer, and this number must be read with suspicion: the generated programs have no inputs, so almost everything is a constant and folding works almost without resistance. In a real program, where the variables come from a file or from a user, the margin is much narrower. Take it as the measure of this generator, not as an estimate of how much a compiler improves real code.

What is missing, and where to go

The language built is deliberately without jumps, and that is why the correctness of the optimizer is easy to argue. With if and while the program becomes a control-flow graph, every register can have two definitions (and the φ function is needed), and analyses such as constant propagation become fixed-point computations on the graph, like FIRST and FOLLOW but on a different structure. A second limit: I used Python's unbounded integers, and a real compiler must respect the 32- or 64-bit arithmetic of the target, so folding has to repeat exactly the overflow the machine would produce. Finally, the IR here is executed by an interpreter, not translated into assembler: instruction selection and the assignment of the machine's registers are missing.

The verification has the same rules as the others in the series: a proof by enumeration or by sampling is not a demonstration, and the check is worth in proportion to its ability to notice an error, which here we measured with the faulty optimizer.

What you can do now, and the path of the series

You can take a tree and check it with a symbol table and a type computation, flatten it into three-address code, write an optimizer with four transformations and explain when each one is lawful. Above all you know why an instruction that can fail is not "dead code", and you can build a comparison among three independent routes that notices defects. The series closes here, and its thread is this: regular expressions describe the tokens, DFAs and NFAs recognize them, context-free grammars describe the structure, the top-down LL(1) and bottom-up LR parsers rebuild it, and this sixth step turns the tree into an executable program. The whole series is on the dedicated page.

Frequently asked questions

Why is semantic analysis a separate step from parsing?

Because what it checks, such as "this name was declared earlier" or "both operands are ints", cannot be expressed with a context-free grammar. The parser verifies the form, semantic analysis visits the tree with a symbol table and checks the meaning.

Why can an optimization not remove a division whose result is not needed?

Because division by zero stops the program, and it is an observable effect. In the listing, treating division as pure makes 445 programs out of 5,000 give a different output. It can be removed only if the divisor is a constant other than zero.

What is special about the SSA form?

Every register is written only once, so a definition stays true for the whole program and optimizations become simple substitutions. Where two branches rejoin the φ function is needed, which does not appear here because the language has no jumps.

Sources

Try These Tools

Free developer tools related to this topic.

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects