← Workshop home / Exercise 04
EXERCISE 04

Escape Analysis & Inlining — The Greedy Inliner

Tune the inlining budget, measure binary size, and find the runtime's hard ceiling.

Exercise 4: Escape Analysis & Inlining — The Greedy Inliner

Want to learn more? The Go compiler’s inlining pass lives in go/src/cmd/compile/internal/inline/, and escape analysis in go/src/cmd/compile/internal/escape/. The cost model and its tuning constants are all in inl.go. The -gcflags="-m" flag lets you watch both inlining and escape decisions.

In this exercise, you’ll first see why inlining matters beyond removing call overhead — it unlocks escape analysis, letting values stay on the stack instead of the heap. Then you’ll tune the inliner’s cost model and observe the effect directly on the size of the Go toolchain binary itself, using the Go compiler as its own test subject.

Learning Objectives

By the end of this exercise, you will:

  • Understand what inlining is and how Go’s inliner decides what to inline
  • See how inlining gives escape analysis the visibility to keep values off the heap
  • Know where the inlining cost-model constants live and what each one does
  • Measure how inlining aggressiveness affects compiled binary size
  • See, end to end, that “more inlining = bigger binary” is a real, measurable trade-off
  • Discover the hard ceiling the runtime imposes on how aggressive the inliner can be

Introduction: Inlining and the Cost Model

Inlining replaces a function call with the body of the called function. Instead of:

call add(a, b)   →  jump to add's code, push stack frame, execute, return, pop stack frame

the compiler inserts the body directly:

result = a + b   (inline: no call overhead, no stack frame)

Inlining is one of the most important optimizations in the compiler: it removes call overhead and, just as importantly, exposes the inlined code to other optimizations (escape analysis, constant folding, dead-code elimination) that can only see across a call boundary once the call is gone.

But inlining isn’t free. Every time the compiler inlines a function, it copies that function’s body into the caller. Inline too much and the binary balloons, instruction caches thrash, and compile times grow. So the compiler uses a cost model: it estimates how “expensive” a function is to inline and only inlines it when the estimate is below a budget.

That cost model is just a handful of integer constants. In this exercise we’ll change them and watch the binary size move.

Understanding the Inlining Parameters

All the tuning knobs are gathered in one const block in go/src/cmd/compile/internal/inline/inl.go:

grep -n "inlineMaxBudget\|inlineExtraCallCost\|inlineBigFunctionMaxCost" go/src/cmd/compile/internal/inline/inl.go | head

The three we’ll focus on:

Constant Default What it controls
inlineMaxBudget 80 The cost ceiling. A function whose estimated cost exceeds this is not inlined.
inlineExtraCallCost 57 How much each function call inside a candidate adds to its cost. This dominates most decisions — a couple of calls and you’re already near the budget.
inlineBigFunctionMaxCost 20 The much stricter budget used when inlining into an already-“big” function (one with more than inlineBigFunctionNodes = 5000 nodes).

There are several more in the same block — inlineParamCallCost, inlineExtraPanicCost, inlineExtraThrowCost, inlineClosureCalledOnceCost, etc. Skim them; the comments explain what each is for. We’ll leave those at their defaults.

The cost of a function is computed by walking its AST and summing per-node costs: simple statements are cheap, calls cost inlineExtraCallCost, and so on. If the total stays under inlineMaxBudget, the function is inlinable.

Step 1: See Inlining Unlock Escape Analysis

Before we touch any parameters, let’s see why inlining is worth caring about. Removing call overhead is nice, but the bigger win is that inlining lets escape analysis — the pass that decides whether a value lives on the cheap stack or the expensive, GC-managed heap — see through a call boundary. When a function is not inlined, escape analysis must conservatively assume the worst about the values it returns. When it is inlined, the full dataflow is visible and a value that looked like it had to escape can stay on the stack.

The cleanest way to see this directly is to measure allocations with a benchmark, comparing two identical factory functions — one forced not to inline.

This step uses the default toolchain — no rebuild. If you haven’t built Go yet from a previous exercise, run cd go/src && ./make.bash first. Run the commands below from a scratch directory sitting next to go/, so that ../go/bin/go resolves to your freshly built compiler.

Create a benchmark in its own module directory, next to go/ (here the _test.go suffix is correct — go test requires it):

cd ..                       # back out of escape-demo, next to go/
mkdir -p alloc-test && cd alloc-test
../go/bin/go mod init alloctest

alloc_test.go:

package main

import "testing"

type Point struct{ X, Y float64 }

//go:noinline
func newPointNoInline(x, y float64) *Point { p := Point{X: x, Y: y}; return &p }

func newPoint(x, y float64) *Point { p := Point{X: x, Y: y}; return &p }

func distance(p *Point) float64 { return p.X*p.X + p.Y*p.Y }

func BenchmarkNoInline(b *testing.B) {
    var sink float64
    for i := 0; i < b.N; i++ {
        p := newPointNoInline(3, 4)
        sink += distance(p)
    }
    _ = sink
}

func BenchmarkInline(b *testing.B) {
    var sink float64
    for i := 0; i < b.N; i++ {
        p := newPoint(3, 4)
        sink += distance(p)
    }
    _ = sink
}

Run it:

../go/bin/go test -bench=. -benchmem -run='^$'

Expected (numbers vary by machine):

BenchmarkNoInline-32    175719189    6.200 ns/op    16 B/op    1 allocs/op
BenchmarkInline-32      1000000000   0.199 ns/op     0 B/op    0 allocs/op

There it is: newPointNoInline allocates on the heap (1 alloc/op), while the inlinable newPoint does not (0 allocs/op). Same code — the only difference is whether the compiler could inline it and let escape analysis see that p never actually outlives main. That is why inlining matters. Now let’s explore the knob that controls how much of it happens.

Step 2: Establish a Baseline

First, build the toolchain with the default parameters and record the size of the resulting go binary. We’ll compare every later build against this.

cd go/src
./make.bash
cp ../bin/go ../bin/go-default
wc -c ../bin/go-default

Note the byte count. On the reference machine this was about 23.3 MB (23258260 bytes). Your exact number will differ by platform and Go version — what matters is the relative change in the experiments below.

Each experiment follows the same loop: edit the three constants in inl.go, run ./make.bash, then copy the freshly built ../bin/go to a uniquely named file so you can compare sizes at the end.

Step 3: Aggressive Inlining

Make the inliner more eager. Open go/src/cmd/compile/internal/inline/inl.go and set:

inlineMaxBudget          = 95   // was 80
inlineExtraCallCost      = 40   // was 57
inlineBigFunctionMaxCost = 30   // was 20

A bigger budget, a cheaper per-call cost, and more room inside big functions — all three push toward more inlining. Rebuild and save:

cd go/src
./make.bash
cp ../bin/go ../bin/go-aggressive
wc -c ../bin/go-aggressive

Expected: the build succeeds, and the binary is larger than the default — the compiler inlined more code into more places. On the reference machine: ~24.2 MB (24224649), roughly +4%.

Step 4: Conservative Inlining

Now go the other way. Revert and set the opposite extreme — a small budget and an expensive per-call cost:

git checkout go/src/cmd/compile/internal/inline/inl.go

Then edit inl.go:

inlineMaxBudget          = 40    // was 80
inlineExtraCallCost      = 100   // was 57
inlineBigFunctionMaxCost = 5     // was 20

Rebuild and save:

cd go/src
./make.bash
cp ../bin/go ../bin/go-conservative
wc -c ../bin/go-conservative

Expected: the build succeeds, and the binary is smaller than the default — many functions that used to be inlined now stay as real calls. On the reference machine: ~21.3 MB (21343582), roughly −8%.

Step 5: (Almost) No Inlining

Push conservatism to its limit: a zero budget and a per-call cost so high nothing fits.

git checkout go/src/cmd/compile/internal/inline/inl.go

Then edit inl.go:

inlineMaxBudget          = 0      // was 80
inlineExtraCallCost      = 1000   // was 57
inlineBigFunctionMaxCost = 0      // was 20

Rebuild and save:

cd go/src
./make.bash
cp ../bin/go ../bin/go-no-inline
wc -c ../bin/go-no-inline

Expected: the build still succeeds (the compiler can always not inline), and this is the smallest binary of all — almost every call remains a call. On the reference machine: ~20.1 MB (20102542), roughly −14%.

Step 6: The Extreme — Where the Build Breaks

So far, more aggressive meant “bigger but fine.” Surely we can crank it further? Let’s find out. Revert and set absurdly aggressive values:

git checkout go/src/cmd/compile/internal/inline/inl.go

Then edit inl.go:

inlineMaxBudget          = 500   // was 80
inlineExtraCallCost      = 5     // was 57
inlineBigFunctionMaxCost = 200   // was 20

Rebuild:

cd go/src
./make.bash

This time the build FAILS. You’ll see a wall of errors like:

runtime/mgc.go:751:13: write barrier prohibited by caller; gcStart
runtime/mgcmark.go:514:13: write barrier prohibited by caller; gcAssistAlloc
runtime/malloc.go:1712:17: write barrier prohibited by caller; mallocgcLarge
runtime/mprof.go:318:10: lostStk escapes to heap, not allowed in runtime
go tool dist: FAILED: ... exit status 2

Why? make.bash recompiles the entire standard library — including the runtime — with your modified compiler. The runtime is special: many of its functions are annotated //go:nowritebarrier / //go:nowritebarrierrec (they run at moments when the garbage collector’s write barrier must not fire), and some are forbidden from allocating on the heap entirely. With the default cost model the inliner is conservative enough to respect those boundaries. Crank it this far and the inliner starts pulling write-barrier’d or heap-allocating code into functions that aren’t allowed to contain it — and the compiler rejects it outright.

This is the real lesson: the inlining parameters are not free knobs. The runtime’s correctness invariants impose a hard ceiling on how aggressive the standard inliner can be tuned, which is exactly why the Go team picked the careful defaults it did.

Step 7: Compare the Results

Line up every binary you built:

cd go
wc -c bin/go-default bin/go-aggressive bin/go-conservative bin/go-no-inline

You should see a clear monotonic ordering — no-inline smallest, then conservative, then default, then aggressive largest. From the reference machine:

Variant inlineMaxBudget / ExtraCallCost / BigFunctionMaxCost Binary size Δ vs default
no-inline 0 / 1000 / 0 20,102,542 −13.6%
conservative 40 / 100 / 5 21,343,582 −8.2%
default 80 / 57 / 20 23,258,260 —
aggressive 95 / 40 / 30 24,224,649 +4.2%
extreme 500 / 5 / 200 build fails —

The takeaway: inlining aggressiveness maps directly and predictably onto binary size, and the runtime sets the upper bound on how far you can go.

Cleanup

Restore the original parameters, rebuild a clean toolchain, and delete the experiment binaries:

cd go/src/cmd/compile/internal/inline
git checkout inl.go
cd ../../../../   # back to go/src
./make.bash
rm -f ../bin/go-default ../bin/go-aggressive ../bin/go-conservative ../bin/go-no-inline

And remove the Step 1 scratch directory (from next to go/):

rm -rf alloc-test

Summary

Key file:    go/src/cmd/compile/internal/inline/inl.go  (const block, ~lines 49–61)
Knobs:       inlineMaxBudget (80), inlineExtraCallCost (57), inlineBigFunctionMaxCost (20)

Aggressive (95/40/30):    builds, ~+4%  binary
Conservative (40/100/5):  builds, ~-8%  binary
No inlining (0/1000/0):   builds, ~-14% binary  (smallest)
Extreme (500/5/200):      FAILS — runtime write-barrier invariants forbid it

Measure with: wc -c ../bin/go-*

The inliner’s defaults are a carefully chosen balance: aggressive enough to make real programs fast, conservative enough that the runtime itself still compiles. Tuning them is a one-line change — understanding the consequences is the whole exercise.


Continue to Exercise 5

← Previous
Parser — Multiple 'go' Keywords
Next →
SSA & Compiler Backend — Power-of-Two Detector