How to generate code for a particular CPU?

There’s a common feature in programming languages to compile code for a certain CPU target. This is present in C, Rust, Zig, Haskell, Pascal, and a lot more. Does Go support this at all?

I know gc was built on top of the Plan9 toolchain, not LLVM or GCC… So if there’s no way to target code for a certain CPU (or even tune) in gc, would it be possible in GCC’s frontend, gccgo?

TL;DR set GOOS and GOARCH env vars to desired target

Besides the standard GOOS and GOARCH settings, there are a couple of environment variables for fine-tuning:

go command - cmd/go - > Scroll down to “Architecture-specific environment variables”.

	For GOARCH=arm, the ARM architecture for which to compile.
	Valid values are 5, 6, 7.
	For GOARCH=386, how to implement floating point instructions.
	Valid values are sse2 (default), softfloat.
	For GOARCH=amd64, the microarchitecture level for which to compile.
	Valid values are v1 (default), v2, v3, v4.
	For GOARCH=mips{,le}, whether to use floating point instructions.
	Valid values are hardfloat (default), softfloat.
	For GOARCH=mips64{,le}, whether to use floating point instructions.
	Valid values are hardfloat (default), softfloat.
	For GOARCH=ppc64{,le}, the target ISA (Instruction Set Architecture).
	Valid values are power8 (default), power9.
	For GOARCH=wasm, comma-separated list of experimental WebAssembly features to use.
	Valid values are satconv, signext.

Thank you both!! I have a few follow up questions.

Will for example, setting GO(arch), ie, GOAMD64="v2" have any effects on an other architecture, for example PowerPC, compiling for itself?

As this seems the only way to optimize Go code for your hardware, are there any other ways to optimize Go code? (in general or for your hardware)

This is very unconventional compared to how I see other languages handle this, although it is a lot better than not being able to do this at all. Thanks again for your time.

I think that is pretty clear that the value of GOAMD64 is only effective when GOARCH=amd64.

There’s no -O1, -O2 etc. You can pass gcflags to disable optimizations (-N) or inlining (-l) compile command - cmd/compile -

FWIW The Go compiler needs to be smarter – Daniel Lemire's blog

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.