CodeBlanks Logo Icon CodeBlanks

SSA

Learn the Static Single Assignment intermediate representation.

SSA

SSA (Static Single Assignment) is an intermediate form where each variable is assigned exactly once. x = 1; x = x + 2 becomes x1 = 1; x2 = x1 + 2. This form makes these optimizations easy for the compiler:

  • Constant folding: 2 * 3 → 6
  • Dead code elimination: unused computations are dropped
  • Bounds check elimination (BCE): checks are removed on slice accesses that can be proven safe

A BCE hint

Accessing the largest index once before the reads lets the compiler prove the following accesses safe:

func topla4(b []byte) int {
    _ = b[3]  // the only check is here
    return int(b[0]) + int(b[1]) + int(b[2]) + int(b[3])
}

go build -gcflags="-d=ssa/check_bce" shows the remaining bounds checks line by line. GOSSAFUNC=topla4 go build draws every SSA pass as HTML.

Practice BCE-friendly function

Write oku32(b []byte) uint32: first _ = b[3], then combine the four bytes little-endian: uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24. Print oku32([]byte{1, 0, 0, 0}).

Starter code

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import "fmt"

func oku32(b []byte) uint32 {
    _ = b[3]
    return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
}

func main() {
    fmt.Println(oku32([]byte{1, 0, 0, 0}))
}

Expected output

1

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does bounds check elimination (BCE) remove?

  • Unused imports
  • Comment lines
  • The panic check on index accesses proven safe Correct answer
  • All error checks

Explanation: Every s[i] access normally includes an i < len(s) check; if the compiler proves it always holds, it removes the check.

2 Bounds hint

Question
func f(b []byte) byte {
    _ = b[____]
    return b[0] ^ b[1] ^ b[2] ^ b[7]
}
Answer
func f(b []byte) byte {
    _ = b[7]
    return b[0] ^ b[1] ^ b[2] ^ b[7]
}

Explanation: Accessing the largest index used (7) proves the other indexes safe too.

3 Optimization

Term Meaning
Sabit katlama 2*3 → 6
Dead code elimination Unused computation dropped
BCE Index check removed
GOSSAFUNC Shows SSA passes

All lessons in Expert