Semantic analysis and code generation
Introducido
5:58
Teoría de la computación y compiladores
This course asks what machines can decide, and how text becomes meaning. The first three units are theory: automata and regular languages, context-free…
Narración en inglés · subtítulos en inglés y 中文 que puedes cambiar
En esta lección
| English | Significado |
|---|---|
| symbol table/ˈsɪmbl ˈteɪbl/ | tabla de símbolos |
| scope/skəʊp/ | The region of a program in which a particular name or binding can be accessed. |
| intermediate representation/ˌɪntəˈmiːdɪət ˌreprɪˈzenteɪʃn/ | representación intermedia |
| three-address code/θriː əˈdres kəʊd/ | intermediate code in which each instruction has at most one operator and three addresses |
| lexer/ˈleksə/ | the compiler stage that groups characters into tokens |
| Constant folding/ˈkɒnstənt ˈfəʊldɪŋ/ | working out constant expressions at compile time |
| constant propagation/ˈkɒnstənt ˌprɒpəˈɡeɪʃn/ | replacing a variable with its known constant value |
| dead-code elimination/ded kəʊd ɪˌlɪmɪˈneɪʃn/ | removing code whose results are never used |
| common subexpressions/ˈkɒmən ˌsʌbɪkˈspreʃnz/ | identical expressions computed more than once, which the compiler can compute once |
| Register allocation/ˈredʒɪstə ˌæləˈkeɪʃn/ | choosing which values live in the processor's limited registers |
| spilled/spɪld/ | (of a value) kept in memory because no register is free for it |
| live/laɪv/ | of a variable at a program point: its current value may still be read later |
| Loop-invariant code motion/luːp ɪnˈveərɪənt kəʊd ˈməʊʃn/ | moving a calculation that gives the same result every time out of a loop |
Anotar con significado
- La tabla de símbolos mapea identificadores a (tipo, alcance); las reglas de tipo recorren el árbol de abajo hacia arriba: $\mathbf{id} + \mathbf{id}$ necesita ambos lados numéricos. La salida es una representación intermedia — código de tres direcciones, una operación por línea.


The symbol table binds —
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
Name resolution before type checking: scoping first.
El programa del curso, exactamente
count = a1 + b2 * 3cona1, b2: int: la tabla contiene tres enlaces int; el camina verifica $b_2 \times 3$ luego $a_1 + (\ldots)$. RI:t1 = b2 * 3; t2 = a1 + t1; count = t2— tres instrucciones, un temporal, generado automáticamente.- Intercambiar
b2porstr: el caminante rechazab2 * 3con la posición del analizador léxico, ya que las posiciones son la moneda de error del pipeline.
count = a1 + b2 * 3 emits IR —
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
Three-address: one operation per line, two temps here.
Por qué una IR
- La traducción directa multiplica: $m$ lenguajes × $\times$ × $n$ objetivos = $mn$ compiladores; una IR lo reduce a $m + n$. Las optimizaciones residen en la IR: el plegado es solo literal ($2 \times 3 \to 6$; $b_2 \times 3$ permanece), y cada optimización es una demostración sobre la semántica de la IR.
- Verificar nombres antes que tipos (escope primero), decorar completamente antes de emitir, y nunca plegar a través de operandos no literales.
Constant folding applies to —
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
b2 * 3 stays: b2 is not a literal - folding is literal-only.
Esta tarjeta es nueva, por eso aparece en inglés hasta que su traducción esté lista.
Optimise, then allocate registers
- Simple IR optimisations: constant propagation 常量传播 and folding turn
a = 3; b = a + 4; c = b * 2intoc = 14; dead-code elimination 死代码消除 removesaandbif nothing else reads them; removing common subexpressions 公共子表达式 computesx * yonly once. - Register allocation 寄存器分配 is graph colouring: variables that are alive at the same time interfere and need different registers. Three variables that are all alive together form a triangle and need $3$ registers; if there are fewer, one is spilled 溢出 to memory.
After constant propagation and folding, what value does d hold in a = 5; b = a * 2; d = b - 3?
Dificultad 2/5 · 140 monedas + un pequeño bono en el primer intento de hoy
b = 10, so d = 10 - 3 = 7.
Four variables are all alive at the same time. What is the minimum number of registers to hold them without spilling?
Dificultad 2/5 · 140 monedas + un pequeño bono en el primer intento de hoy
They form a 4-clique in the interference graph, which needs 4 colours.
Put the compiler phases in order.
Dificultad 3/5 · 200 monedas + un pequeño bono en el primer intento de hoy
Each phase consumes the one before: tokens, then a tree, then a checked tree, then IR. Optimising on the IR lets every source language and target share the same passes.
Esta tarjeta es nueva, por eso aparece en inglés hasta que su traducción esté lista.
Liveness decides the registers
- A variable is live 活跃 at a point if its value may still be read later. In
a = 1; b = a + 2; c = b * a; return c, after line 2 both $a$ and $b$ are live; after line 3 only $c$ is. - At most two values are live at once, so two registers are enough: $c$ can reuse $b$'s register. Liveness is computed backwards from the uses.
a = 1; b = a + 2; c = b * a; return c: the most values live at one point?
Dificultad 2/5 · 140 monedas + un pequeño bono en el primer intento de hoy
After line 2, $a$ y $b$; after line 3, only $c$.
Esta tarjeta es nueva, por eso aparece en inglés hasta que su traducción esté lista.
Worked example: moving work out of a loop
for i in 0..999: x = y * z; a[i] = x + icomputesy * za thousand times, although neither $y$ nor $z$ changes in the loop.- Loop-invariant code motion 循环不变量外提 computes it once before the loop: $\mathbf{999}$ multiplications saved.
x + idepends on $i$, so it must stay inside.
A loop of 1000 iterations computes y * z each time, with $y$ y $z$ unchanged. Multiplications saved by hoisting it?
Dificultad 2/5 · 140 monedas + un pequeño bono en el primer intento de hoy
One before the loop instead of 1000 inside.
In that loop, x + i can also be hoisted out.
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
It depends on $i$, which changes every iteration.
Esta tarjeta es nueva, por eso aparece en inglés hasta que su traducción esté lista.
Marks that slip away
- Types before names. Resolve scopes 作用域 first; a type check on an undeclared name has nothing to check.
- Folding non-literals.
2 * 3folds to6;b2 * 3cannot fold, becauseb2is known only at run time. - Assuming every temporary gets a register. When live values outnumber registers, the allocator spills some to memory.
Esta tarjeta es nueva, por eso aparece en inglés hasta que su traducción esté lista.
Recap
- The symbol table 符号表 maps names to type and scope; check names before types.
- Three-address IR:
t1 = b2 * 3; t2 = a1 + t1; count = t2. - An IR turns $m \times n$ compilers into $m + n$; fold only literal operands. For 3 languages and 4 targets:
| Design | You write |
|---|---|
| Direct | $3 \times 4 = 12$ compilers |
| Through an IR | $3 + 4 = 7$ parts |
¿Qué salió mal? Solo el equipo del sitio ve esta información.