A Quick Guide to Go's Assembler
A Quick Guide to Go's Assembler
This document is a quick outline of the unusual form of assembly language used by thegc Go compiler.The document is not comprehensive.
The assembler is based on the input style of the Plan 9 assemblers, which is documented in detailelsewhere.If you plan to write assembly language, you should read that document although much of it is Plan 9-specific.The current document provides a summary of the syntax and the differences withwhat is explained in that document, anddescribes the peculiarities that apply when writing assembly code to interact with Go.
The most important thing to know about Go's assembler is that it is not a direct representation of the underlying machine.Some of the details map precisely to the machine, but some do not.This is because the compiler suite (seethis description)needs no assembler pass in the usual pipeline.Instead, the compiler operates on a kind of semi-abstract instruction set,and instruction selection occurs partly after code generation.The assembler works on the semi-abstract form, sowhen you see an instruction likeMOVwhat the toolchain actually generates for that operation mightnot be a move instruction at all, perhaps a clear or load.Or it might correspond exactly to the machine instruction with that name.In general, machine-specific operations tend to appear as themselves, while more general concepts likememory move and subroutine call and return are more abstract.The details vary with architecture, and we apologize for the imprecision; the situation is not well-defined.
The assembler program is a way to parse a description of thatsemi-abstract instruction set and turn it into instructions to beinput to the linker.If you want to see what the instructions look like in assembly for a given architecture, say amd64, thereare many examples in the sources of the standard library, in packages such asruntime andmath/big.You can also examine what the compiler emits as assembly code(the actual output may differ from what you see here):
$ cat x.gopackage mainfunc main() {println(3)}$ GOOS=linux GOARCH=amd64 go tool compile -S x.go # or: go build -gcflags -S x.go"".main STEXT size=74 args=0x0 locals=0x100x0000 00000 (x.go:3)TEXT"".main(SB), $16-00x0000 00000 (x.go:3)MOVQ(TLS), CX0x0009 00009 (x.go:3)CMPQSP, 16(CX)0x000d 00013 (x.go:3)JLS670x000f 00015 (x.go:3)SUBQ$16, SP0x0013 00019 (x.go:3)MOVQBP, 8(SP)0x0018 00024 (x.go:3)LEAQ8(SP), BP0x001d 00029 (x.go:3)FUNCDATA$0, gclocals·33cdeccccebe80329f1fdbee7f5874cb(SB)0x001d 00029 (x.go:3)FUNCDATA$1, gclocals·33cdeccccebe80329f1fdbee7f5874cb(SB)0x001d 00029 (x.go:3)FUNCDATA$2, gclocals·33cdeccccebe80329f1fdbee7f5874cb(SB)0x001d 00029 (x.go:4)PCDATA$0, $00x001d 00029 (x.go:4)PCDATA$1, $00x001d 00029 (x.go:4)CALLruntime.printlock(SB)0x0022 00034 (x.go:4)MOVQ$3, (SP)0x002a 00042 (x.go:4)CALLruntime.printint(SB)0x002f 00047 (x.go:4)CALLruntime.printnl(SB)0x0034 00052 (x.go:4)CALLruntime.printunlock(SB)0x0039 00057 (x.go:5)MOVQ8(SP), BP0x003e 00062 (x.go:5)ADDQ$16, SP0x0042 00066 (x.go:5)RET0x0043 00067 (x.go:5)NOP0x0043 00067 (x.go:3)PCDATA$1, $-10x0043 00067 (x.go:3)PCDATA$0, $-10x0043 00067 (x.go:3)CALLruntime.morestack_noctxt(SB)0x0048 00072 (x.go:3)JMP0...TheFUNCDATA andPCDATA directives contain informationfor use by the garbage collector; they are introduced by the compiler.
To see what gets put in the binary after linking, usego tool objdump:
$ go build -o x.exe x.go$ go tool objdump -s main.main x.exeTEXT main.main(SB) /tmp/x.go x.go:30x10501c065488b0c2530000000MOVQ GS:0x30, CX x.go:30x10501c9483b6110CMPQ 0x10(CX), SP x.go:30x10501cd7634JBE 0x1050203 x.go:30x10501cf4883ec10SUBQ $0x10, SP x.go:30x10501d348896c2408MOVQ BP, 0x8(SP) x.go:30x10501d8488d6c2408LEAQ 0x8(SP), BP x.go:40x10501dde86e45fdffCALL runtime.printlock(SB) x.go:40x10501e248c7042403000000MOVQ $0x3, 0(SP) x.go:40x10501eae8e14cfdffCALL runtime.printint(SB) x.go:40x10501efe8ec47fdffCALL runtime.printnl(SB) x.go:40x10501f4e8d745fdffCALL runtime.printunlock(SB) x.go:50x10501f9488b6c2408MOVQ 0x8(SP), BP x.go:50x10501fe4883c410ADDQ $0x10, SP x.go:50x1050202c3RET x.go:30x1050203e83882ffffCALL runtime.morestack_noctxt(SB) x.go:30x1050208ebb6JMP main.main(SB)
Constants
Although the assembler takes its guidance from the Plan 9 assemblers,it is a distinct program, so there are some differences.One is in constant evaluation.Constant expressions in the assembler are parsed using Go's operatorprecedence, not the C-like precedence of the original.Thus3&1<<2 is 4, not 0—it parses as(3&1)<<2not3&(1<<2).Also, constants are always evaluated as 64-bit unsigned integers.Thus-2 is not the integer value minus two,but the unsigned 64-bit integer with the same bit pattern.The distinction rarely matters butto avoid ambiguity, division or right shift where the right operand'shigh bit is set is rejected.
Symbols
Some symbols, such asR1 orLR,are predefined and refer to registers.The exact set depends on the architecture.
There are four predeclared symbols that refer to pseudo-registers.These are not real registers, but rather virtual registers maintained bythe toolchain, such as a frame pointer.The set of pseudo-registers is the same for all architectures:
FP: Frame pointer: arguments and locals.PC: Program counter:jumps and branches.SB: Static base pointer: global symbols.SP: Stack pointer: the highest address within the local stack frame.
All user-defined symbols are written as offsets to the pseudo-registersFP (arguments and locals) andSB (globals).
TheSB pseudo-register can be thought of as the origin of memory, so the symbolfoo(SB)is the namefoo as an address in memory.This form is used to name global functions and data.Adding<> to the name, as infoo<>(SB), makes the namevisible only in the current source file, like a top-levelstatic declaration in a C file.Adding an offset to the name refers to that offset from the symbol's address, sofoo+4(SB) is four bytes past the start offoo.
TheFP pseudo-register is a virtual frame pointerused to refer to function arguments.The compilers maintain a virtual frame pointer and refer to the arguments on the stack as offsets from that pseudo-register.Thus0(FP) is the first argument to the function,8(FP) is the second (on a 64-bit machine), and so on.However, when referring to a function argument this way, it is necessary to place a nameat the beginning, as infirst_arg+0(FP) andsecond_arg+8(FP).(The meaning of the offset—offset from the frame pointer—distinctfrom its use withSB, where it is an offset from the symbol.)The assembler enforces this convention, rejecting plain0(FP) and8(FP).The actual name is semantically irrelevant but should be used to documentthe argument's name.It is worth stressing thatFP is always apseudo-register, not a hardwareregister, even on architectures with a hardware frame pointer.
For assembly functions with Go prototypes,govet will check that the argument namesand offsets match.On 32-bit systems, the low and high 32 bits of a 64-bit value are distinguished by addinga_lo or_hi suffix to the name, as inarg_lo+0(FP) orarg_hi+4(FP).If a Go prototype does not name its result, the expected assembly name isret.
TheSP pseudo-register is a virtual stack pointerused to refer to frame-local variables and the arguments beingprepared for function calls.It points to the highest address within the local stack frame, so references should use negative offsetsin the range [−framesize, 0):x-8(SP),y-4(SP), and so on.
On architectures with a hardware register namedSP,the name prefix distinguishesreferences to the virtual stack pointer from references to the architecturalSP register.That is,x-8(SP) and-8(SP)are different memory locations:the first refers to the virtual stack pointer pseudo-register,while the second refers to thehardware'sSP register.
On machines whereSP andPC aretraditionally aliases for a physical, numbered register,in the Go assembler the namesSP andPCare still treated specially;for instance, references toSP require a symbol,much likeFP.To access the actual hardware register use the trueR name.For example, on the ARM architecture the hardwareSP andPC are accessible asR13 andR15.
Branches and direct jumps are always written as offsets to the PC, or asjumps to labels:
label:MOVW $0, R1JMP label
Each label is visible only within the function in which it is defined.It is therefore permitted for multiple functions in a file to defineand use the same label names.Direct jumps and call instructions can target text symbols,such asname(SB), but not offsets from symbols,such asname+4(SB).
Instructions, registers, and assembler directives are always in UPPER CASE to remind youthat assembly programming is a fraught endeavor.(Exception: theg register renaming on ARM.)
In Go object files and binaries, the full name of a symbol is thepackage path followed by a period and the symbol name:fmt.Printf ormath/rand.Int.Because the assembler's parser treats period and slash as punctuation,those strings cannot be used directly as identifier names.Instead, the assembler allows the middle dot character U+00B7and the division slash U+2215 in identifiers and rewrites them toplain period and slash.Within an assembler source file, the symbols above are written asfmt·Printf andmath∕rand·Int.The assembly listings generated by the compilers when using the-S flagshow the period and slash directly instead of the Unicode replacementsrequired by the assemblers.
Most hand-written assembly files do not include the full package pathin symbol names, because the linker inserts the package path of the currentobject file at the beginning of any name starting with a period:in an assembly source file within the math/rand package implementation,the package's Int function can be referred to as·Int.This convention avoids the need to hard-code a package's import path in itsown source code, making it easier to move the code from one location to another.
Directives
The assembler uses various directives to bind text and data to symbol names.For example, here is a simple complete function definition. TheTEXTdirective declares the symbolruntime·profileloop and the instructionsthat follow form the body of the function.The last instruction in aTEXT block must be some sort of jump, usually aRET (pseudo-)instruction.(If it's not, the linker will append a jump-to-itself instruction; there is no fallthrough inTEXTs.)After the symbol, the arguments are flags (see below)and the frame size, a constant (but see below):
TEXT runtime·profileloop(SB),NOSPLIT,$8MOVQ$runtime·profileloop1(SB), CXMOVQCX, 0(SP)CALLruntime·externalthreadhandler(SB)RET
In the general case, the frame size is followed by an argument size, separated by a minus sign.(It's not a subtraction, just idiosyncratic syntax.)The frame size$24-8 states that the function has a 24-byte frameand is called with 8 bytes of argument, which live on the caller's frame.IfNOSPLIT is not specified for theTEXT,the argument size must be provided.For assembly functions with Go prototypes,govet will check that theargument size is correct.
Note that the symbol name uses a middle dot to separate the components and is specified as an offset from thestatic base pseudo-registerSB.This function would be called from Go source for packageruntime using thesimple nameprofileloop.
Global data symbols are defined by a sequence of initializingDATA directives followed by aGLOBL directive.EachDATA directive initializes a section of thecorresponding memory.The memory not explicitly initialized is zeroed.The general form of theDATA directive is
DATAsymbol+offset(SB)/width, value
which initializes the symbol memory at the given offset and width with the given value.TheDATA directives for a given symbol must be written with increasing offsets.
TheGLOBL directive declares a symbol to be global.The arguments are optional flags and the size of the data being declared as a global,which will have initial value all zeros unless aDATA directivehas initialized it.TheGLOBL directive must follow any correspondingDATA directives.
For example,
DATA divtab<>+0x00(SB)/4, $0xf4f8fcffDATA divtab<>+0x04(SB)/4, $0xe6eaedf0...DATA divtab<>+0x3c(SB)/4, $0x81828384GLOBL divtab<>(SB), RODATA, $64GLOBL runtime·tlsoffset(SB), NOPTR, $4
declares and initializesdivtab<>, a read-only 64-byte table of 4-byte integer values,and declaresruntime·tlsoffset, a 4-byte, implicitly zeroed variable thatcontains no pointers.
There may be one or two arguments to the directives.If there are two, the first is a bit mask of flags,which can be written as numeric expressions, added or or-ed together,or can be set symbolically for easier absorption by a human.Their values, defined in the standard#include filetextflag.h, are:
NOPROF= 1
(ForTEXTitems.)Don't profile the marked function. This flag is deprecated.DUPOK= 2
It is legal to have multiple instances of this symbol in a single binary.The linker will choose one of the duplicates to use.NOSPLIT= 4
(ForTEXTitems.)Don't insert the preamble to check if the stack must be split.The frame for the routine, plus anything it calls, must fit in thespare space remaining in the current stack segment.Used to protect routines such as the stack splitting code itself.RODATA= 8
(ForDATAandGLOBLitems.)Put this data in a read-only section.NOPTR= 16
(ForDATAandGLOBLitems.)This data contains no pointers and therefore does not need to bescanned by the garbage collector.WRAPPER= 32
(ForTEXTitems.)This is a wrapper function and should not count as disablingrecover.NEEDCTXT= 64
(ForTEXTitems.)This function is a closure so it uses its incoming context register.LOCAL= 128
This symbol is local to the dynamic shared object.TLSBSS= 256
(ForDATAandGLOBLitems.)Put this data in thread local storage.NOFRAME= 512
(ForTEXTitems.)Do not insert instructions to allocate a stack frame and save/restore the returnaddress, even if this is not a leaf function.Only valid on functions that declare a frame size of 0.TOPFRAME= 2048
(ForTEXTitems.)Function is the outermost frame of the call stack. Traceback should stop at this function.
Special instructions
ThePCALIGN pseudo-instruction is used to indicate that the next instruction should be alignedto a specified boundary by padding with no-op instructions.
It is currently supported on arm64, amd64, ppc64, loong64 and riscv64.For example, the start of theMOVD instruction below is aligned to 32 bytes:
PCALIGN $32MOVD $2, R0
Interacting with Go types and constants
If a package has any .s files, thengo build will directthe compiler to emit a special header calledgo_asm.h,which the .s files can then#include.The file contains symbolic#define constants for theoffsets of Go struct fields, the sizes of Go struct types, and mostGoconst declarations defined in the current package.Go assembly should avoid making assumptions about the layout of Gotypes and instead use these constants.This improves the readability of assembly code, and keeps it robust tochanges in data layout either in the Go type definitions or in thelayout rules used by the Go compiler.
Constants are of the formconst_name.For example, given the Go declarationconst bufSize =1024, assembly code can refer to the value of this constantasconst_bufSize.
Field offsets are of the formtype_field.Struct sizes are of the formtype__size.For example, consider the following Go definition:
type reader struct {buf [bufSize]byter int}Assembly can refer to the size of this structasreader__size and the offsets of the two fieldsasreader_buf andreader_r.Hence, if registerR1 contains a pointer toareader, assembly can reference ther fieldasreader_r(R1).
If any of these#define names are ambiguous (for example,a struct with a_size field),#include"go_asm.h" will fail with a "redefinition of macro" error.
Runtime Coordination
For garbage collection to run correctly, the runtime must know thelocation of pointers in all global data and in most stack frames.The Go compiler emits this information when compiling Go source files,but assembly programs must define it explicitly.
A data symbol marked with theNOPTR flag (see above)is treated as containing no pointers to runtime-allocated data.A data symbol with theRODATA flagis allocated in read-only memory and is therefore treatedas implicitly markedNOPTR.A data symbol with a total size smaller than a pointeris also treated as implicitly markedNOPTR.It is not possible to define a symbol containing pointers in an assembly source file;such a symbol must be defined in a Go source file instead.Assembly source can still refer to the symbol by nameeven withoutDATA andGLOBL directives.A good general rule of thumb is to define all non-RODATAsymbols in Go instead of in assembly.
Each function also needs annotations giving the location oflive pointers in its arguments, results, and local stack frame.For an assembly function with no pointer results andeither no local stack frame or no function calls,the only requirement is to define a Go prototype for the functionin a Go source file in the same package. The name of the assemblyfunction must not contain the package name component (for example,functionSyscall in packagesyscall shoulduse the name·Syscall instead of the equivalent namesyscall·Syscall in itsTEXT directive).For more complex situations, explicit annotation is needed.These annotations use pseudo-instructions defined in the standard#include filefuncdata.h.
If a function has no arguments and no results,the pointer information can be omitted.This is indicated by an argument size annotation of$n-0on theTEXT instruction.Otherwise, pointer information must be provided bya Go prototype for the function in a Go source file,even for assembly functions not called directly from Go.(The prototype will also letgovet check the argument references.)At the start of the function, the arguments are assumedto be initialized but the results are assumed uninitialized.If the results will hold live pointers during a call instruction,the function should start by zeroing the results and thenexecuting the pseudo-instructionGO_RESULTS_INITIALIZED.This instruction records that the results are now initializedand should be scanned during stack movement and garbage collection.It is typically easier to arrange that assembly functions do notreturn pointers or do not contain call instructions;no assembly functions in the standard library useGO_RESULTS_INITIALIZED.
If a function has no local stack frame,the pointer information can be omitted.This is indicated by a local frame size annotation of$0-non theTEXT instruction.The pointer information can also be omitted if thefunction contains no call instructions.Otherwise, the local stack frame must not contain pointers,and the assembly must confirm this fact by executing thepseudo-instructionNO_LOCAL_POINTERS.Because stack resizing is implemented by moving the stack,the stack pointer may change during any function call:even pointers to stack data must not be kept in local variables.
Assembly functions should always be given Go prototypes,both to provide pointer information for the arguments and resultsand to letgovet check thatthe offsets being used to access them are correct.
Architecture-specific details
It is impractical to list all the instructions and other details for each machine.To see what instructions are defined for a given machine, say ARM,look in the source for theobj support library forthat architecture, located in the directorysrc/cmd/internal/obj/arm.In that directory is a filea.out.go; it containsa long list of constants starting withA, like this:
const (AAND = obj.ABaseARM + obj.A_ARCHSPECIFIC + iotaAEORASUBARSBAADD...
This is the list of instructions and their spellings as known to the assembler and linker for that architecture.Each instruction begins with an initial capitalA in this list, soAANDrepresents the bitwise and instruction,AND (without the leadingA),and is written in assembly source asAND.The enumeration is mostly in alphabetical order.(The architecture-independentAXXX, defined in thecmd/internal/obj package,represents an invalid instruction).The sequence of theA names has nothing to do with the actualencoding of the machine instructions.Thecmd/internal/obj package takes care of that detail.
The instructions for both the 386 and AMD64 architectures are listed incmd/internal/obj/x86/a.out.go.
The architectures share syntax for common addressing modes such as(R1) (register indirect),4(R1) (register indirect with offset), and$foo(SB) (absolute address).The assembler also supports some (not necessarily all) addressing modesspecific to each architecture.The sections below list these.
One detail evident in the examples from the previous sections is that data in the instructions flows from left to right:MOVQ$0,CX clearsCX.This rule applies even on architectures where the conventional notation uses the opposite direction.
Here follow some descriptions of key Go-specific details for the supported architectures.
32-bit Intel 386
The runtime pointer to theg structure is maintainedthrough the value of an otherwise unused (as far as Go is concerned) register in the MMU.In the runtime package, assembly code can includego_tls.h, which definesan OS- and architecture-dependent macroget_tls for accessing this register.Theget_tls macro takes one argument, which is the register to load theg pointer into.
For example, the sequence to loadg andmusingCX looks like this:
#include "go_tls.h"#include "go_asm.h"...get_tls(CX)MOVLg(CX), AX // Move g into AX.MOVLg_m(AX), BX // Move g.m into BX.
Theget_tls macro is also defined onamd64.
Addressing modes:
(DI)(BX*2): The location at addressDIplusBX*2.64(DI)(BX*2): The location at addressDIplusBX*2plus 64.These modes accept only 1, 2, 4, and 8 as scale factors.
When using the compiler and assembler's-dynlink or-shared modes,any load or store of a fixed memory location such as a global variablemust be assumed to overwriteCX.Therefore, to be safe for use with these modes,assembly sources should typically avoid CX except between memory references.
64-bit Intel 386 (a.k.a. amd64)
The two architectures behave largely the same at the assembler level.Assembly code to access them andgpointers on the 64-bit version is the same as on the 32-bit 386,except it usesMOVQ rather thanMOVL:
get_tls(CX)MOVQg(CX), AX // Move g into AX.MOVQg_m(AX), BX // Move g.m into BX.
RegisterBP is callee-save.The assembler automatically insertsBP save/restore when frame size is larger than zero.UsingBP as a general purpose register is allowed,however it can interfere with sampling-based profiling.
ARM
The registersR10 andR11are reserved by the compiler and linker.
R10 points to theg (goroutine) structure.Within assembler source code, this pointer must be referred to asg;the nameR10 is not recognized.
To make it easier for people and compilers to write assembly, the ARM linkerallows general addressing forms and pseudo-operations likeDIV orMODthat may not be expressible using a single hardware instruction.It implements these forms as multiple instructions, often using theR11 registerto hold temporary values.Hand-written assembly can useR11, but doing so requiresbeing sure that the linker is not also using it to implement any of the otherinstructions in the function.
When defining aTEXT, specifying frame size$-4tells the linker that this is a leaf function that does not need to saveLR on entry.
The nameSP always refers to the virtual stack pointer described earlier.For the hardware register, useR13.
Condition code syntax is to append a period and the one- or two-letter code to the instruction,as inMOVW.EQ.Multiple codes may be appended:MOVM.IA.W.The order of the code modifiers is irrelevant.
Addressing modes:
R0->16R0>>16R0<<16R0@>16:For<<, left shiftR0by 16 bits.The other codes are->(arithmetic right shift),>>(logical right shift), and@>(rotate right).R0->R1R0>>R1R0<<R1R0@>R1:For<<, left shiftR0by the count inR1.The other codes are->(arithmetic right shift),>>(logical right shift), and@>(rotate right).[R0,g,R12-R15]: For multi-register instructions, the set comprisingR0,g, andR12throughR15inclusive.(R5, R6): Destination register pair.
ARM64
R18 is the "platform register", reserved on the Apple platform.To prevent accidental misuse, the register is namedR18_PLATFORM.R27 andR28 are reserved by the compiler and linker.R29 is the frame pointer.R30 is the link register.
Instruction modifiers are appended to the instruction following a period.The only modifiers areP (postincrement) andW(preincrement):MOVW.P,MOVW.W
Addressing modes:
R0->16R0>>16R0<<16R0@>16:These are the same as on the 32-bit ARM.$(8<<12):Left shift the immediate value8by12bits.8(R0):Add the value ofR0and8.(R2)(R0):The location atR0plusR2.R0.UXTBR0.UXTB<<imm:UXTB: extract an 8-bit value from the low-order bits ofR0and zero-extend it to the size ofR0.R0.UXTB<<imm: left shift the result ofR0.UXTBbyimmbits.Theimmvalue can be 0, 1, 2, 3, or 4.The other extensions includeUXTH(16-bit),UXTW(32-bit), andUXTX(64-bit).R0.SXTBR0.SXTB<<imm:SXTB: extract an 8-bit value from the low-order bits ofR0and sign-extend it to the size ofR0.R0.SXTB<<imm: left shift the result ofR0.SXTBbyimmbits.Theimmvalue can be 0, 1, 2, 3, or 4.The other extensions includeSXTH(16-bit),SXTW(32-bit), andSXTX(64-bit).(R5, R6): Register pair forLDAXP/LDP/LDXP/STLXP/STP/STP.
Reference:Go ARM64 Assembly Instructions Reference Manual
PPC64
This assembler is used by GOARCH values ppc64 and ppc64le.
Reference:Go PPC64 Assembly Instructions Reference Manual
IBM z/Architecture, a.k.a. s390x
The registersR10 andR11 are reserved.The assembler uses them to hold temporary values when assembling some instructions.
R13 points to theg (goroutine) structure.This register must be referred to asg; the nameR13 is not recognized.
R15 points to the stack frame and should typically only be accessed using thevirtual registersSP andFP.
Load- and store-multiple instructions operate on a range of registers.The range of registers is specified by a start register and an end register.For example,LMG(R9),R5,R7 would loadR5,R6 andR7 with the 64-bit values at0(R9),8(R9) and16(R9) respectively.
Storage-and-storage instructions such asMVC andXC are writtenwith the length as the first argument.For example,XC$8,(R9),(R9) would cleareight bytes at the address specified inR9.
If a vector instruction takes a length or an index as an argument then it will be thefirst argument.For example,VLEIF$1,$16,V2 will loadthe value sixteen into index one ofV2.Care should be taken when using vector instructions to ensure that they are available atruntime.To use vector instructions a machine must have both the vector facility (bit 129 in thefacility list) and kernel support.Without kernel support a vector instruction will have no effect (it will be equivalentto aNOP instruction).
Addressing modes:
(R5)(R6*1): The location atR5plusR6.It is a scaled mode as on the x86, but the only scale allowed is1.
MIPS, MIPS64
General purpose registers are namedR0 throughR31,floating point registers areF0 throughF31.
R30 is reserved to point tog.R23 is used as a temporary register.
In aTEXT directive, the frame size$-4 for MIPS or$-8 for MIPS64 instructs the linker not to saveLR.
SP refers to the virtual stack pointer.For the hardware register, useR29.
Addressing modes:
16(R1): The location atR1plus 16.(R1): Alias for0(R1).
The value ofGOMIPS environment variable (hardfloat orsoftfloat) is made available to assembly code by predefining eitherGOMIPS_hardfloat orGOMIPS_softfloat.
The value ofGOMIPS64 environment variable (hardfloat orsoftfloat) is made available to assembly code by predefining eitherGOMIPS64_hardfloat orGOMIPS64_softfloat.
RISCV64
Reference:Go RISCV64 Assembly Instructions Reference Manual
Unsupported opcodes
The assemblers are designed to support the compiler so not all hardware instructionsare defined for all architectures: if the compiler doesn't generate it, it might not be there.If you need to use a missing instruction, there are two ways to proceed.One is to update the assembler to support that instruction, which is straightforwardbut only worthwhile if it's likely the instruction will be used again.Instead, for simple one-off cases, it's possible to use theBYTEandWORD directivesto lay down explicit data into the instruction stream within aTEXT.Here's how the 386 runtime defines the 64-bit atomic load function.
// uint64 atomicload64(uint64 volatile* addr);// so actually// void atomicload64(uint64 *res, uint64 volatile *addr);TEXT runtime·atomicload64(SB), NOSPLIT, $0-12MOVLptr+0(FP), AXTESTL$7, AXJZ2(PC)MOVL0, AX // crash with nil ptr derefLEALret_lo+4(FP), BX// MOVQ (%EAX), %MM0BYTE $0x0f; BYTE $0x6f; BYTE $0x00// MOVQ %MM0, 0(%EBX)BYTE $0x0f; BYTE $0x7f; BYTE $0x03// EMMSBYTE $0x0F; BYTE $0x77RET