Explain lowering, register allocation and machine code
Explain lowering, register allocation and machine code
Lowering rewrites generic SSA operations into operations suitable for the target CPU. Register allocation chooses physical registers for values and may spill values into stack slots when registers are insufficient. Frame layout and pointer liveness information support stack use and garbage collection. The assembler encodes instructions into machine code. Instruction selection, calling convention and register names depend on the target architecture and compiler version.
package main
import ( "fmt")
//go:noinlinefunc mix(a, b uint64) uint64 { return (a + b) * 3 }func main() { fmt.Println(mix(4, 5))}Save as main.go. Run go build -gcflags=-S -o demo main.go 2>asm.txt and go tool objdump -s "main\.mix$" demo. The first shows compiler assembly and the second disassembles the linked symbol. On amd64, arithmetic may use LEA or ADD instructions; do not expect a particular mnemonic. The tool output is Go assembly notation rather than portable source code. The noinline directive retains a callable symbol for inspection.
Expected output:
27Compare target architectures
package main
import ( "fmt" "math/bits")
//go:noinlinefunc rotate(x uint64) uint64 { return bits.RotateLeft64(x, 8) }func main() { fmt.Printf("%016x\n", rotate(0x0123456789abcdef))}On a Linux host build this source with CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o demo-amd64 main.go and repeat for GOARCH=arm64 with output demo-arm64. Inspect both using go tool objdump and the rotate symbol. A rotate may lower to a CPU-specific instruction; the documented bit rotation is the same. Cross-building does not execute the foreign binary. Register spills require evidence from a particular function; a large argument list alone does not prove a spill.
Expected output:
23456789abcdef01Try it locally
Implement a noinline uint64 function that returns (a ^ b) + 1; print the result for 6 and 3. Build and inspect its disassembly on your own architecture.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Compiler pipeline 07: Explain lowering, register allocation and machine code
Check the lesson objective before moving on.
What does register allocation decide?
Why may the same Go function disassemble differently on amd64 and arm64?