Source file src/cmd/cgo/abi.go

     1  // Copyright 2026 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package main
     6  
     7  import (
     8  	"cmp"
     9  	"fmt"
    10  	"go/ast"
    11  	"go/parser"
    12  	"go/token"
    13  	"internal/buildcfg"
    14  	"io"
    15  	"os"
    16  	"slices"
    17  	"strconv"
    18  	"strings"
    19  )
    20  
    21  // BindingType describes a C or Go type used by cgo binding declarations
    22  // for C ABI classification and Go wrapper generation.
    23  type BindingType struct {
    24  	Name        string // Mangled C type name (e.g. "_Ctype_foo") or Go helper type name
    25  	Def         string // Underlying Go type expression (e.g. "int32", "struct { a float32 }"); empty if opaque
    26  	Size        int64  // Size in bytes on the target architecture
    27  	Align       int64  // Alignment in bytes on the target architecture
    28  	HasPointers bool   // Whether the type contains pointers (for GC keepalives and callback return zeroing)
    29  }
    30  
    31  // BindingFunc describes a C function bound with //cgo:func, either a
    32  // function linked with the program or a method of a //cgo:dynload type that
    33  // calls a function in a library loaded at run time, or an exported Go
    34  // callback (//export).
    35  type BindingFunc struct {
    36  	// Identifier and symbol names:
    37  	Name   string // Internal cgo function identifier (used in _Cfunc_<Name>, _cgo_arg_<Name>, and _cgo_trampoline_<Name>)
    38  	GoName string // Go function named by the //cgo:func pragma (used by binding.go)
    39  	CName  string // Target C symbol name
    40  	BindC  bool   // The pragma wrote the C name as C.<CName>, so Go code may also call the function as C.<CName> (used by binding.go)
    41  
    42  	// Signature (Go type expressions, e.g. "int32", "*byte", "_Ctype_S"):
    43  	Params []string // Declared parameter types
    44  	Ret    string   // Return type expression, or "" for void
    45  
    46  	// Calling convention modifiers (used by ABI layout and trampoline generation):
    47  	Indirect    bool // Call target address is passed at offset 0 of the Go arg struct (//cgo:dynload methods)
    48  	MayCallback bool // C call may re-enter Go; spills pointer-passed args/returns to g0 stack and tracks _cgo_topofstack
    49  
    50  	// Go wrapper and import metadata (used by binding.go):
    51  	Library string // Shared library or DLL name for dynamic import directives; empty for libc and static
    52  	LibC    bool   // The symbol comes from the platform C runtime (libc)
    53  	Static  bool   // The symbol is resolved at link time from a .syso or .a (static)
    54  
    55  	// Methods of //cgo:dynload types (used by binding.go):
    56  	RecvType string // The //cgo:dynload type, for a //cgo:func LibT.GoName pragma
    57  	SymIndex int    // Index of the symbol in RecvType's per-instance symbol table
    58  }
    59  
    60  // ParamLoc describes where a function parameter is passed in the C ABI.
    61  type ParamLoc struct {
    62  	GoOffset   int64    // Byte offset in Go _cgo_arg_<Name> struct
    63  	Size       int64    // Parameter size in bytes
    64  	IsFloat    bool     // Floating-point parameter
    65  	Regs       []string // Register(s) if passed in register(s) (or leading register half of a split param)
    66  	StackOff   int64    // Byte offset in C stack frame when passed on the stack (or trailing stack half when StackBytes > 0)
    67  	StackBytes int64    // Trailing byte count placed on the stack when a composite splits across Regs and stack
    68  	PassByPtr  bool     // True if passed by hidden reference (pointer in Regs[0] or on stack)
    69  	G0Off      int64    // Scratch offset on g0 stack when MayCallback && PassByPtr
    70  }
    71  
    72  // RetLoc describes how a function return value is returned in the C ABI.
    73  type RetLoc struct {
    74  	GoOffset        int64    // Byte offset in Go _cgo_arg_<Name> struct
    75  	Size            int64    // Return value size in bytes
    76  	IsFloat         bool     // Floating-point return
    77  	Indirect        bool     // True if caller passes a hidden sret return buffer pointer
    78  	IndirectOnStack bool     // True if hidden sret pointer is passed at 0(SP) (386 ABI)
    79  	Regs            []string // Register(s) holding the return value upon C return (e.g. AX, X0)
    80  	G0Off           int64    // Scratch offset on g0 stack when MayCallback
    81  }
    82  
    83  // FuncLayout describes the complete Go argument struct and C ABI layout for a call.
    84  type FuncLayout struct {
    85  	Params        []ParamLoc
    86  	Ret           RetLoc
    87  	StackSize     int64 // C stack frame size in bytes (aligned to ABIConfig.StackAlign)
    88  	FloatRegCount int   // Number of floating-point argument registers allocated (for SysV AMD64 AX)
    89  	StkTopOff     int64 // Saved _cgo_topofstack slot on g0 stack when MayCallback
    90  }
    91  
    92  // hasStackArgs reports whether any argument is passed on the C stack.
    93  func (lay FuncLayout) hasStackArgs() bool {
    94  	if lay.Ret.IndirectOnStack {
    95  		return true
    96  	}
    97  	for _, p := range lay.Params {
    98  		if (p.Size > 0 && len(p.Regs) == 0) || p.StackBytes > 0 {
    99  			return true
   100  		}
   101  	}
   102  	return false
   103  }
   104  
   105  // abiState tracks register and stack allocation cursors while computing a FuncLayout.
   106  type abiState struct {
   107  	intIdx       int
   108  	floatIdx     int
   109  	vfpMask      uint16 // bitmask of allocated S0..S15 VFP lanes (32-bit ARM only)
   110  	stackOff     int64
   111  	fprsDisabled bool // disables FPR arg allocation once a non-float/sret arg or F14 is used (32-bit MIPS O32 only)
   112  }
   113  
   114  // leafField represents a single scalar leaf within a flattened composite type.
   115  type leafField struct {
   116  	offset  int64
   117  	size    int64
   118  	align   int64
   119  	isFloat bool
   120  	signed  bool
   121  	direct  bool // Scalar member of the enclosing struct itself, not flattened from an array, nested struct, or complex type
   122  }
   123  
   124  // typeInfo holds the byte size, alignment, ABI classification, and flattened
   125  // scalar leaves of a type.
   126  type typeInfo struct {
   127  	size              int64
   128  	align             int64
   129  	isFloat           bool
   130  	signed            bool
   131  	composite         bool
   132  	isComplex         bool // complex64 or complex128 (C _Complex float or _Complex double)
   133  	isStruct          bool // Go struct type (C struct), as opposed to an array, complex, or scalar type
   134  	directFields      int  // Number of members of a struct type, not counting structs.HostLayout
   135  	singleFloatStruct bool // Struct whose only member is a float32, float64, or such a struct
   136  	hasPointers       bool
   137  	fields            []leafField
   138  	fieldsOK          bool
   139  }
   140  
   141  // regSlot describes a single register piece of a parameter or return value.
   142  type regSlot struct {
   143  	reg         string
   144  	offset      int64 // Byte offset relative to ParamLoc.GoOffset or RetLoc.GoOffset
   145  	size        int64 // Byte size of this piece (1..8)
   146  	align       int64 // Guaranteed alignment of the backing field (0 means PtrSize)
   147  	isFloat     bool
   148  	signed      bool
   149  	leftJustify bool // Big-endian composite piece < PtrSize is left-justified in the upper bytes of reg
   150  }
   151  
   152  // asmOps defines the assembly mnemonics for an architecture's load, store,
   153  // shift, arithmetic, and stack-pointer operations.
   154  type asmOps struct {
   155  	mov        string // Pointer-sized integer load/store/reg-move (e.g. "MOVQ", "MOVD")
   156  	loadB      string // Signed 1-byte load
   157  	loadBU     string // Unsigned 1-byte load
   158  	loadH      string // Signed 2-byte load
   159  	loadHU     string // Unsigned 2-byte load
   160  	loadW      string // Signed 4-byte load
   161  	loadWU     string // Unsigned 4-byte load
   162  	storeB     string // 1-byte store
   163  	storeH     string // 2-byte store
   164  	storeW     string // 4-byte store
   165  	fmovS      string // 32-bit float load/store
   166  	fmovD      string // 64-bit float load/store
   167  	shl        string // Left shift mnemonic (e.g. "SHLQ", "LSL", "SLL")
   168  	shr        string // Logical right shift mnemonic (e.g. "SHRQ", "LSR", "SRL")
   169  	or         string // Bitwise OR mnemonic (e.g. "ORQ", "ORR", "OR")
   170  	add        string // Add mnemonic (e.g. "ADDQ", "ADD", "ADDV", "ADDU")
   171  	sub        string // Subtract mnemonic (e.g. "SUBQ", "SUB", "SUBV", "SUBU")
   172  	lea        string // Effective-address mnemonic on x86 ("LEAQ", "LEAL"), or "" to use add
   173  	twoOpALU   bool   // True if or/add/sub take 2 operands (src, dst) rather than 3 (src, dst, dst)
   174  	twoOpShift bool   // True if shl/shr take 2 operands ($bits, reg) rather than 3 ($bits, reg, reg)
   175  	useAdjSP   bool   // True if SP adjustments must use ADJSP so obj tracks pcsp without FuncFlagSPWrite
   176  	negSubSP   bool   // True if decrementing SP uses add with $-size rather than sub with $size
   177  	alignDisp4 bool   // True if 8-byte loads/stores and signed 4-byte loads require 4-byte-aligned displacements (PPC64 DS-form)
   178  }
   179  
   180  // ABIConfig defines the C calling convention rules and assembly primitives
   181  // for a target OS/architecture. OS, PtrSize, CLongSize, StackAlign, and AssignParam must always be set.
   182  type ABIConfig struct {
   183  	Arch             string
   184  	OS               string
   185  	PtrSize          int64
   186  	CLongSize        int64 // Byte size of C long and unsigned long
   187  	StackAlign       int64
   188  	ShadowSpace      int64 // Bytes reserved at the bottom of the C call frame by the ABI (e.g. 32-byte home space on Windows x64)
   189  	MinParamSaveArea int64 // Minimum parameter save area reserved above ShadowSpace before g0 scratch (64B on PPC64/AIX)
   190  
   191  	IntRegs      []string
   192  	FloatRegs    []string
   193  	IntRetRegs   []string
   194  	FloatRetRegs []string
   195  
   196  	MaxRegStructSize   int64
   197  	IndirectRetReg     string // Register holding hidden sret buffer pointer
   198  	IndirectRetInArg   bool   // Hidden sret pointer consumes IntRegs[0]
   199  	IndirectRetOnStack bool   // Hidden sret pointer is passed at 0(SP) (386)
   200  	SysVI386SretPop    bool   // Callee pops 4B sret pointer on return (SysV 386)
   201  	PackStackArgs      bool   // Pack narrow scalar and HFA stack args at natural alignment (Apple ARM64)
   202  
   203  	// AssignParam allocates a single parameter in registers or on the C stack.
   204  	AssignParam func(cfg *ABIConfig, fn BindingFunc, idx int, info typeInfo, st *abiState) ParamLoc
   205  
   206  	// AssignRet determines how the return value is returned in the C ABI.
   207  	// ABIs without special return rules use defaultAssignRet.
   208  	AssignRet func(cfg *ABIConfig, fn BindingFunc, info typeInfo, st *abiState) RetLoc
   209  
   210  	// Optional platform-specific ABI hook. Returning handled=false falls back
   211  	// to default GPR chunking.
   212  	CompositeRegSlots func(cfg *ABIConfig, info typeInfo, isFloat bool, regs []string) ([]regSlot, bool)
   213  
   214  	// Trampoline and callback assembly generation parameters:
   215  	SPReg           string // Hardware stack pointer register in asm (e.g. "SP", "RSP", "R1", "X2")
   216  	CalleeSavedReg  string // C callee-saved register holding the Go _cgo_arg struct pointer across C calls
   217  	TmpReg          string // Primary caller-saved scratch register for stack/memory copies and address math
   218  	TmpReg2         string // Secondary caller-saved scratch register for multi-chunk loads and copies
   219  	IndCallReg      string // Register for indirect C calls when different from TmpReg (e.g. "R25" on MIPS)
   220  	LinkReg         string // Link register saved by default RISC trampoline/callback prologue/epilogue (e.g. "X1", "R31")
   221  	AsmTmpReg       string // Callee-saved assembler REGTMP saved in RISC callback prologue (e.g. "R23", "R30")
   222  	LRReserve       int64  // Bytes reserved at 0(SP) for saved LR when !hasStackArgs and ShadowSpace == 0
   223  	ShadowUsesSlot0 bool   // True if C callees may overwrite 0(SP) inside ShadowSpace (MIPS O32)
   224  	ZeroVal         string // Zero operand or register for zeroing pointer-containing callback return slots, or "" to zero TmpReg
   225  	LocalFrameOff   int64  // Byte offset from SPReg to the local Go arg struct in writeCallbackTrampoline
   226  	IndirectSymCall bool   // External C symbols are PE IAT pointers called indirectly (Windows)
   227  	HasFuncDesc     bool   // C and trampoline symbols use 24-byte (PC, TOC, env) XCOFF descriptors (AIX)
   228  
   229  	BigEndian                    bool // Multi-byte integer chunks in registers and stack slots use big-endian byte order
   230  	LeftJustifyBEComposite       bool // Big-endian composite register chunks < PtrSize are left-justified (MIPS, AIX)
   231  	LeftJustifyBETrailing        bool // Big-endian trailing register chunks of >PtrSize composites are left-justified (ELFv2 BE)
   232  	RightJustifyBECompositeStack bool // Big-endian sub-word composites on the stack are right-justified (s390x, ELFv2 BE)
   233  	LeftJustifyBEFloatStack      bool // Big-endian float32 stack arguments are left-justified in their slot (AIX, MIPS64)
   234  	ComplexFloatSplitStack       bool // The float32 halves of a complex64 stack argument occupy separate PtrSize slots (PPC64)
   235  	SignExtUint32                bool // 32-bit unsigned integers are sign-extended to 64 bits in registers and stack slots (MIPS64, RISC-V, LoongArch)
   236  	StrictAlign                  bool // Architecture traps on unaligned multi-byte loads/stores (MIPS, ARM)
   237  
   238  	asm                asmOps
   239  	IsFloatReg         func(reg string) bool
   240  	LoadFloat          func(w io.Writer, base string, off, size int64, reg string) bool
   241  	StoreFloat         func(w io.Writer, reg, base string, off, size int64) bool
   242  	TrampolinePrologue func(w io.Writer, lay FuncLayout) (epilogue func(w io.Writer))
   243  	Prologue           func(w io.Writer) (epilogue func(w io.Writer))
   244  	PreCall            func(cfg *ABIConfig, w io.Writer, fn BindingFunc, lay FuncLayout)
   245  	CallIndirect       func(w io.Writer, base string)
   246  	CallSymbol         func(w io.Writer, sym string, static bool)
   247  	StackArgAddr       func(stackOff, callerSPOff int64) (base string, off int64)
   248  	CallbackPrologue   func(w io.Writer, frameSize int64) (callerSPOff int64)
   249  	CallbackEpilogue   func(w io.Writer, frameSize int64, sretPop bool)
   250  	CallCrosscall2     func(w io.Writer, fnName string, frameSize, ctxtOff int64)
   251  }
   252  
   253  // isFloatReg reports whether reg is an architecture floating-point register.
   254  func (cfg *ABIConfig) isFloatReg(reg string) bool {
   255  	if cfg.IsFloatReg != nil && cfg.IsFloatReg(reg) {
   256  		return true
   257  	}
   258  	return slices.Contains(cfg.FloatRegs, reg) || slices.Contains(cfg.FloatRetRegs, reg)
   259  }
   260  
   261  // alignUp rounds off up to the next multiple of power-of-two align.
   262  func alignUp(off, align int64) int64 {
   263  	if align <= 1 {
   264  		return off
   265  	}
   266  	return (off + align - 1) &^ (align - 1)
   267  }
   268  
   269  // isHostLayoutExpr reports whether expr is the zero-sized structs.HostLayout
   270  // marker embedded in Go struct definitions for C types.
   271  func isHostLayoutExpr(expr ast.Expr) bool {
   272  	sel, ok := expr.(*ast.SelectorExpr)
   273  	if !ok {
   274  		return false
   275  	}
   276  	id, ok := sel.X.(*ast.Ident)
   277  	return ok && id.Name == "structs" && sel.Sel.Name == "HostLayout"
   278  }
   279  
   280  // ptrTypeInfo returns the typeInfo for a pointer-sized scalar on cfg.
   281  func (cfg *ABIConfig) ptrTypeInfo() typeInfo {
   282  	return typeInfo{
   283  		size:     cfg.PtrSize,
   284  		align:    cfg.PtrSize,
   285  		fields:   []leafField{{size: cfg.PtrSize, align: cfg.PtrSize, direct: true}},
   286  		fieldsOK: true,
   287  	}
   288  }
   289  
   290  // inspectType summarizes the ABI layout properties (size, alignment, float,
   291  // signedness, composite status, and flattened scalar leaves) of Go/cgo type
   292  // expression t under cfg.
   293  func (cfg *ABIConfig) inspectType(t string, types map[string]BindingType) typeInfo {
   294  	if cfg.OS == "" {
   295  		panic("ABIConfig.OS must be set")
   296  	}
   297  	expr, err := parser.ParseExpr(t)
   298  	if err != nil {
   299  		return typeInfo{size: cfg.PtrSize, align: cfg.PtrSize}
   300  	}
   301  	return cfg.inspectExpr(expr, types, nil)
   302  }
   303  
   304  // inspectExpr walks a parsed Go type AST expression to compute its byte size,
   305  // alignment, aggregate classification, and flattened scalar leaf fields.
   306  //
   307  // Go strings, slices, maps, channels, funcs, interfaces, and instantiated
   308  // generic types have no C ABI layout. cTypeError rejects them before any
   309  // layout is computed, so inspectExpr panics if it sees one.
   310  func (cfg *ABIConfig) inspectExpr(expr ast.Expr, types map[string]BindingType, seen map[string]bool) typeInfo {
   311  	if isHostLayoutExpr(expr) {
   312  		return typeInfo{align: 1, fieldsOK: true}
   313  	}
   314  	switch e := expr.(type) {
   315  	case *ast.ParenExpr:
   316  		return cfg.inspectExpr(e.X, types, seen)
   317  	case *ast.StarExpr:
   318  		d := cfg.ptrTypeInfo()
   319  		d.hasPointers = true
   320  		return d
   321  	case *ast.ArrayType:
   322  		if e.Len == nil {
   323  			panic("Go slice type in ABI type")
   324  		}
   325  		// Binding parsing evaluates constant array lengths (such as named constants)
   326  		// to integer literals before calling inspectType.
   327  		lit, ok := e.Len.(*ast.BasicLit)
   328  		if !ok || lit.Kind != token.INT {
   329  			panic("non-integer-literal array length in ABI type")
   330  		}
   331  		n, err := strconv.ParseInt(lit.Value, 0, 64)
   332  		if err != nil || n < 0 {
   333  			panic("invalid array length in ABI type: " + lit.Value)
   334  		}
   335  		ed := cfg.inspectExpr(e.Elt, types, seen)
   336  		if n == 0 {
   337  			return typeInfo{align: ed.align, composite: true, fieldsOK: true}
   338  		}
   339  		if !ed.fieldsOK {
   340  			return typeInfo{size: ed.size * n, align: ed.align, composite: true, hasPointers: ed.hasPointers}
   341  		}
   342  		fields := make([]leafField, 0, int64(len(ed.fields))*n)
   343  		for i := range n {
   344  			delta := i * ed.size
   345  			for _, f := range ed.fields {
   346  				f.offset += delta
   347  				f.direct = false
   348  				fields = append(fields, f)
   349  			}
   350  		}
   351  		return typeInfo{
   352  			size:        ed.size * n,
   353  			align:       ed.align,
   354  			composite:   true,
   355  			hasPointers: ed.hasPointers,
   356  			fields:      fields,
   357  			fieldsOK:    true,
   358  		}
   359  	case *ast.StructType:
   360  		var off int64
   361  		maxAlign := int64(1)
   362  		var fields []leafField
   363  		fieldsOK := true
   364  		hasPointers := false
   365  		nFields := 0
   366  		singleFloat := false
   367  		for _, fld := range e.Fields.List {
   368  			if isHostLayoutExpr(fld.Type) {
   369  				continue
   370  			}
   371  			fd := cfg.inspectExpr(fld.Type, types, seen)
   372  			maxAlign = max(maxAlign, fd.align)
   373  			hasPointers = hasPointers || fd.hasPointers
   374  			if !fd.fieldsOK {
   375  				fieldsOK = false
   376  				fields = nil
   377  			}
   378  			n := max(1, len(fld.Names))
   379  			nFields += n
   380  			singleFloat = nFields == 1 && (fd.isFloat || fd.singleFloatStruct)
   381  			for range n {
   382  				off = alignUp(off, fd.align)
   383  				if fieldsOK {
   384  					for _, f := range fd.fields {
   385  						f.offset += off
   386  						// Leaves of a nested struct are not direct
   387  						// members of this struct.
   388  						f.direct = f.direct && !fd.isStruct
   389  						fields = append(fields, f)
   390  					}
   391  				}
   392  				off += fd.size
   393  			}
   394  		}
   395  		return typeInfo{
   396  			size:              alignUp(off, maxAlign),
   397  			align:             maxAlign,
   398  			composite:         true,
   399  			isStruct:          true,
   400  			directFields:      nFields,
   401  			singleFloatStruct: singleFloat,
   402  			hasPointers:       hasPointers,
   403  			fields:            fields,
   404  			fieldsOK:          fieldsOK,
   405  		}
   406  	case *ast.SelectorExpr:
   407  		if id, ok := e.X.(*ast.Ident); ok {
   408  			if (id.Name == "structs" && e.Sel.Name == "HostLayout") ||
   409  				((id.Name == "_cgopackage" || id.Name == "cgo") && e.Sel.Name == "Incomplete") {
   410  				return typeInfo{align: 1, fieldsOK: true}
   411  			}
   412  			if id.Name == "C" {
   413  				return cfg.inspectTypeName("_Ctype_"+e.Sel.Name, types, seen)
   414  			}
   415  		}
   416  		d := cfg.ptrTypeInfo()
   417  		d.hasPointers = true
   418  		return d
   419  	case *ast.Ident:
   420  		return cfg.inspectTypeName(e.Name, types, seen)
   421  	}
   422  	panic(fmt.Sprintf("unsupported type expression %T in ABI type", expr))
   423  }
   424  
   425  // scalarSpec describes the size and classification of a built-in Go or C scalar type.
   426  type scalarSpec struct {
   427  	size    int64 // Fixed byte size, or 0 when ptr or cLong is set
   428  	ptr     bool  // Size equals ABIConfig.PtrSize
   429  	cLong   bool  // Size equals ABIConfig.CLongSize
   430  	cChar   bool  // Signedness depends on target C ABI (char)
   431  	signed  bool
   432  	isFloat bool
   433  }
   434  
   435  func targetCCharIsUnsigned(os, arch string) bool {
   436  	if os == "darwin" || os == "ios" || os == "windows" {
   437  		return false
   438  	}
   439  	switch arch {
   440  	case "arm", "arm64", "ppc64", "ppc64le", "riscv64", "s390x":
   441  		return true
   442  	}
   443  	return false
   444  }
   445  
   446  var scalarTypes = map[string]scalarSpec{
   447  	"uintptr":          {ptr: true},
   448  	"uint":             {ptr: true},
   449  	"_Ctype_size_t":    {ptr: true},
   450  	"int":              {ptr: true, signed: true},
   451  	"_Ctype_ssize_t":   {ptr: true, signed: true},
   452  	"_Ctype_ptrdiff_t": {ptr: true, signed: true},
   453  	"bool":             {size: 1},
   454  	"uint8":            {size: 1},
   455  	"byte":             {size: 1},
   456  	"_Ctype_uchar":     {size: 1},
   457  	"_Ctype__Bool":     {size: 1},
   458  	"int8":             {size: 1, signed: true},
   459  	"_Ctype_char":      {size: 1, cChar: true},
   460  	"_Ctype_schar":     {size: 1, signed: true},
   461  	"uint16":           {size: 2},
   462  	"_Ctype_ushort":    {size: 2},
   463  	"int16":            {size: 2, signed: true},
   464  	"_Ctype_short":     {size: 2, signed: true},
   465  	"uint32":           {size: 4},
   466  	"_Ctype_uint":      {size: 4},
   467  	"int32":            {size: 4, signed: true},
   468  	"rune":             {size: 4, signed: true},
   469  	"_Ctype_int":       {size: 4, signed: true},
   470  	"_Ctype_ulong":     {cLong: true},
   471  	"_Ctype_long":      {cLong: true, signed: true},
   472  	"uint64":           {size: 8},
   473  	"_Ctype_ulonglong": {size: 8},
   474  	"int64":            {size: 8, signed: true},
   475  	"_Ctype_longlong":  {size: 8, signed: true},
   476  	"float32":          {size: 4, isFloat: true},
   477  	"_Ctype_float":     {size: 4, isFloat: true},
   478  	"float64":          {size: 8, isFloat: true},
   479  	"_Ctype_double":    {size: 8, isFloat: true},
   480  }
   481  
   482  // inspectTypeName resolves a Go or mangled C type identifier into its ABI size,
   483  // alignment, scalar/composite classification, and flattened leaves while
   484  // rejecting recursive type cycles.
   485  func (cfg *ABIConfig) inspectTypeName(name string, types map[string]BindingType, seen map[string]bool) typeInfo {
   486  	if s, ok := scalarTypes[name]; ok {
   487  		sz := s.size
   488  		switch {
   489  		case s.ptr:
   490  			sz = cfg.PtrSize
   491  		case s.cLong:
   492  			if cfg.CLongSize <= 0 {
   493  				panic("ABIConfig.CLongSize must be set")
   494  			}
   495  			sz = cfg.CLongSize
   496  		}
   497  		signed := s.signed
   498  		if s.cChar {
   499  			signed = !targetCCharIsUnsigned(cfg.OS, cfg.Arch)
   500  		}
   501  		align := sz
   502  		if cfg.Arch == "386" && cfg.OS != "windows" {
   503  			align = min(sz, 4)
   504  		}
   505  		d := typeInfo{size: sz, align: align, signed: signed, isFloat: s.isFloat}
   506  		if sz > 0 {
   507  			d.fields = []leafField{{size: d.size, align: d.align, isFloat: d.isFloat, signed: d.signed, direct: true}}
   508  			d.fieldsOK = true
   509  		}
   510  		return d
   511  	}
   512  
   513  	switch name {
   514  	case "string", "any", "error":
   515  		panic("Go type " + name + " in ABI type")
   516  	case "complex64":
   517  		return typeInfo{
   518  			size:      8,
   519  			align:     4,
   520  			composite: true,
   521  			isComplex: true,
   522  			fields: []leafField{
   523  				{offset: 0, size: 4, align: 4, isFloat: true},
   524  				{offset: 4, size: 4, align: 4, isFloat: true},
   525  			},
   526  			fieldsOK: true,
   527  		}
   528  	case "complex128":
   529  		al := cfg.inspectTypeName("float64", nil, nil).align
   530  		return typeInfo{
   531  			size:      16,
   532  			align:     al,
   533  			composite: true,
   534  			isComplex: true,
   535  			fields: []leafField{
   536  				{offset: 0, size: 8, align: al, isFloat: true},
   537  				{offset: 8, size: 8, align: al, isFloat: true},
   538  			},
   539  			fieldsOK: true,
   540  		}
   541  	}
   542  
   543  	bt, ok := types[name]
   544  	if !ok {
   545  		return cfg.ptrTypeInfo()
   546  	}
   547  	if bt.Def == "" {
   548  		return typeInfo{size: bt.Size, align: bt.Align, composite: true, hasPointers: bt.HasPointers}
   549  	}
   550  	if seen[name] {
   551  		return typeInfo{size: bt.Size, align: bt.Align, hasPointers: bt.HasPointers}
   552  	}
   553  	expr, err := parser.ParseExpr(bt.Def)
   554  	if err != nil {
   555  		return typeInfo{size: bt.Size, align: bt.Align, hasPointers: bt.HasPointers}
   556  	}
   557  	if seen == nil {
   558  		seen = make(map[string]bool)
   559  	}
   560  	seen[name] = true
   561  	d := cfg.inspectExpr(expr, types, seen)
   562  	delete(seen, name)
   563  	d.hasPointers = d.hasPointers || bt.HasPointers
   564  	if d.composite && (bt.Size > 0 || bt.Align > 0) {
   565  		d.size, d.align = bt.Size, bt.Align
   566  	}
   567  	return d
   568  }
   569  
   570  // layout computes the Go argument struct layout and C calling convention
   571  // register and stack assignments for fn.
   572  func (cfg *ABIConfig) layout(fn BindingFunc, types map[string]BindingType) FuncLayout {
   573  	if cfg.OS == "" {
   574  		panic("ABIConfig.OS must be set")
   575  	}
   576  	st := abiState{stackOff: cfg.ShadowSpace}
   577  	ret, retAlign := cfg.assignRet(fn, &st, types)
   578  	params, goOff := cfg.assignParams(fn, &st, types)
   579  	if fn.Ret != "" {
   580  		ret.GoOffset = alignUp(goOff, min(retAlign, cfg.PtrSize))
   581  	}
   582  	if cfg.MinParamSaveArea > 0 {
   583  		saveArea := max(cfg.MinParamSaveArea, int64(st.intIdx)*cfg.PtrSize)
   584  		st.stackOff = max(st.stackOff, cfg.ShadowSpace+saveArea)
   585  	}
   586  	stkTopOff := cfg.assignG0Scratch(fn, params, &ret, &st)
   587  
   588  	return FuncLayout{
   589  		Params:        params,
   590  		Ret:           ret,
   591  		StackSize:     alignUp(st.stackOff, cfg.StackAlign),
   592  		FloatRegCount: st.floatIdx,
   593  		StkTopOff:     stkTopOff,
   594  	}
   595  }
   596  
   597  // assignRet determines how fn's return value is returned in the C ABI using
   598  // cfg.AssignRet and returns its alignment in the Go argument struct.
   599  func (cfg *ABIConfig) assignRet(fn BindingFunc, st *abiState, types map[string]BindingType) (RetLoc, int64) {
   600  	if cfg.AssignRet == nil {
   601  		panic("ABIConfig.AssignRet must be set")
   602  	}
   603  	if fn.Ret == "" {
   604  		return RetLoc{}, 1
   605  	}
   606  	info := cfg.inspectType(fn.Ret, types)
   607  	return cfg.AssignRet(cfg, fn, info, st), info.align
   608  }
   609  
   610  // defaultAssignRet implements standard return-value placement. It is used
   611  // directly as AssignRet by ABIs without special composite-return rules, and
   612  // called by ABI-specific AssignRet functions for the cases they do not handle
   613  // themselves (such as scalar returns on amd64, or scalar and non-HFA struct
   614  // returns on arm64).
   615  // Composites exceeding MaxRegStructSize use a hidden sret buffer pointer
   616  // (consuming IntRegs[0] when IndirectRetInArg is set), floats use
   617  // FloatRetRegs[0], and integers or small composites pack into IntRetRegs.
   618  func defaultAssignRet(cfg *ABIConfig, _ BindingFunc, info typeInfo, st *abiState) RetLoc {
   619  	ptrSize := cfg.PtrSize
   620  	if cfg.IndirectRetOnStack && info.composite && info.size > 0 {
   621  		st.stackOff += 4
   622  		return RetLoc{Size: info.size, Indirect: true, IndirectOnStack: true}
   623  	}
   624  	if info.size > cfg.MaxRegStructSize && (!info.isFloat || len(cfg.FloatRetRegs) == 0) && (info.composite || info.size > ptrSize*int64(len(cfg.IntRetRegs))) {
   625  		if cfg.IndirectRetInArg {
   626  			st.intIdx = 1
   627  			st.fprsDisabled = true
   628  		}
   629  		return RetLoc{Size: info.size, Indirect: true}
   630  	}
   631  	if info.isFloat && len(cfg.FloatRetRegs) > 0 {
   632  		return RetLoc{Size: info.size, Regs: []string{cfg.FloatRetRegs[0]}, IsFloat: true}
   633  	}
   634  	if info.size > 0 {
   635  		numRegs := (info.size + ptrSize - 1) / ptrSize
   636  		return RetLoc{Size: info.size, Regs: slices.Clone(cfg.IntRetRegs[:numRegs])}
   637  	}
   638  	return RetLoc{}
   639  }
   640  
   641  // assignParams allocates C ABI registers or stack offsets and Go argument
   642  // struct offsets for each parameter of fn in left-to-right order, returning
   643  // the parameter locations and the Go struct byte offset after the last parameter.
   644  func (cfg *ABIConfig) assignParams(fn BindingFunc, st *abiState, types map[string]BindingType) ([]ParamLoc, int64) {
   645  	if cfg.AssignParam == nil {
   646  		panic("ABIConfig.AssignParam must be set")
   647  	}
   648  	var goOff int64
   649  	if fn.Indirect {
   650  		goOff = cfg.PtrSize
   651  	}
   652  	paramTypes := fn.Params
   653  	params := make([]ParamLoc, len(paramTypes))
   654  	for i, pt := range paramTypes {
   655  		info := cfg.inspectType(pt, types)
   656  		loc := cfg.AssignParam(cfg, fn, i, info, st)
   657  		goOff = alignUp(goOff, min(info.align, cfg.PtrSize))
   658  		loc.GoOffset = goOff
   659  		goOff += loc.Size
   660  		params[i] = loc
   661  	}
   662  	return params, goOff
   663  }
   664  
   665  // assignFloatParam allocates a floating-point scalar parameter to the next
   666  // available register in cfg.FloatRegs, or to an aligned C stack slot.
   667  func (cfg *ABIConfig) assignFloatParam(info typeInfo, st *abiState) ParamLoc {
   668  	if st.floatIdx < len(cfg.FloatRegs) {
   669  		reg := cfg.FloatRegs[st.floatIdx]
   670  		st.floatIdx++
   671  		return ParamLoc{Size: info.size, IsFloat: true, Regs: []string{reg}}
   672  	}
   673  	if cfg.PackStackArgs {
   674  		return cfg.assignPackedStackParam(info.size, info.align, true, st)
   675  	}
   676  	return cfg.assignStackParam(info.size, true, st)
   677  }
   678  
   679  // assignIntParam allocates an integer scalar or small composite parameter
   680  // across consecutive registers in cfg.IntRegs, or to an aligned C stack slot.
   681  func (cfg *ABIConfig) assignIntParam(info typeInfo, st *abiState) ParamLoc {
   682  	if info.size == 0 {
   683  		return ParamLoc{}
   684  	}
   685  	numRegs := int((info.size + cfg.PtrSize - 1) / cfg.PtrSize)
   686  	if st.intIdx+numRegs <= len(cfg.IntRegs) {
   687  		regs := slices.Clone(cfg.IntRegs[st.intIdx : st.intIdx+numRegs])
   688  		st.intIdx += numRegs
   689  		return ParamLoc{Size: info.size, Regs: regs}
   690  	}
   691  	// Apple ARM64 packs narrow scalar stack arguments at natural alignment,
   692  	// while non-HFA composites <= 16 bytes still occupy PtrSize-aligned slots.
   693  	if cfg.PackStackArgs && !info.composite {
   694  		return cfg.assignPackedStackParam(info.size, info.align, false, st)
   695  	}
   696  	return cfg.assignStackParam(info.size, false, st)
   697  }
   698  
   699  // assignPtrParam passes a composite of size bytes by hidden pointer in the next
   700  // available register in cfg.IntRegs, or in a pointer-sized C stack slot.
   701  func (cfg *ABIConfig) assignPtrParam(size int64, st *abiState) ParamLoc {
   702  	if st.intIdx < len(cfg.IntRegs) {
   703  		reg := cfg.IntRegs[st.intIdx]
   704  		st.intIdx++
   705  		return ParamLoc{Size: size, PassByPtr: true, Regs: []string{reg}}
   706  	}
   707  	off := alignUp(st.stackOff, cfg.PtrSize)
   708  	st.stackOff = off + cfg.PtrSize
   709  	return ParamLoc{Size: size, PassByPtr: true, StackOff: off}
   710  }
   711  
   712  // assignPackedStackParam allocates size bytes on the C argument stack at
   713  // natural alignment without rounding the slot up to PtrSize (Apple ARM64).
   714  func (cfg *ABIConfig) assignPackedStackParam(size, align int64, isFloat bool, st *abiState) ParamLoc {
   715  	off := alignUp(st.stackOff, max(align, 1))
   716  	st.stackOff = off + size
   717  	return ParamLoc{Size: size, IsFloat: isFloat, StackOff: off}
   718  }
   719  
   720  // assignStackParam allocates size bytes on the C argument stack aligned to PtrSize.
   721  func (cfg *ABIConfig) assignStackParam(size int64, isFloat bool, st *abiState) ParamLoc {
   722  	off := alignUp(st.stackOff, cfg.PtrSize)
   723  	st.stackOff = off + alignUp(size, cfg.PtrSize)
   724  	return ParamLoc{Size: size, IsFloat: isFloat, StackOff: off}
   725  }
   726  
   727  // assignG0Scratch reserves scratch space on the g0 stack frame when MayCallback
   728  // is true so pointer-passed arguments, indirect return buffers, and the saved
   729  // _cgo_topofstack pointer survive Go stack growth during C-to-Go callbacks.
   730  func (cfg *ABIConfig) assignG0Scratch(fn BindingFunc, params []ParamLoc, ret *RetLoc, st *abiState) int64 {
   731  	if !fn.MayCallback {
   732  		return 0
   733  	}
   734  	needsScratch := fn.Ret != "" && ret.Size > 0
   735  	for i := range params {
   736  		if params[i].PassByPtr {
   737  			needsScratch = true
   738  			break
   739  		}
   740  	}
   741  	if !needsScratch {
   742  		return 0
   743  	}
   744  	if cfg.LRReserve > 0 && st.stackOff == 0 {
   745  		// Leave 0..LRReserve-1(SP) free for the trampoline's saved LR slot
   746  		// when no C stack arguments or ABI shadow space occupy 0(SP).
   747  		st.stackOff = cfg.LRReserve
   748  	}
   749  	ptrSize := cfg.PtrSize
   750  	for i := range params {
   751  		if params[i].PassByPtr {
   752  			st.stackOff = alignUp(st.stackOff, ptrSize)
   753  			params[i].G0Off = st.stackOff
   754  			st.stackOff += alignUp(params[i].Size, ptrSize)
   755  		}
   756  	}
   757  	var stkTopOff int64
   758  	if fn.Ret != "" && ret.Size > 0 {
   759  		st.stackOff = alignUp(st.stackOff, ptrSize)
   760  		ret.G0Off = st.stackOff
   761  		st.stackOff += alignUp(ret.Size, ptrSize)
   762  		stkTopOff = st.stackOff
   763  		st.stackOff += ptrSize
   764  	}
   765  	return stkTopOff
   766  }
   767  
   768  // decomposePow2Aligned splits a byte size (1..8) into descending power-of-two
   769  // chunks bounded by maxWidth (1, 2, 4, or 8).
   770  func decomposePow2Aligned(size, maxWidth int64) []int64 {
   771  	var chunks []int64
   772  	for rem := size; rem > 0; {
   773  		ck := maxPow2Chunk(rem, maxWidth)
   774  		chunks = append(chunks, ck)
   775  		rem -= ck
   776  	}
   777  	return chunks
   778  }
   779  
   780  // maxPow2Chunk returns the largest power-of-two byte width (1, 2, 4, or 8)
   781  // that fits within both rem and maxWidth.
   782  func maxPow2Chunk(rem, maxWidth int64) int64 {
   783  	if maxWidth >= 8 && rem >= 8 {
   784  		return 8
   785  	}
   786  	if maxWidth >= 4 && rem >= 4 {
   787  		return 4
   788  	}
   789  	if maxWidth >= 2 && rem >= 2 {
   790  		return 2
   791  	}
   792  	return 1
   793  }
   794  
   795  // effAlign returns the guaranteed power-of-two alignment of base+off given the
   796  // backing field's alignment (0 means ptrSize).
   797  func effAlign(off, align, ptrSize int64) int64 {
   798  	if align <= 0 || align > ptrSize {
   799  		align = ptrSize
   800  	}
   801  	if off != 0 {
   802  		offAlign := off & -off
   803  		if offAlign < align {
   804  			align = offAlign
   805  		}
   806  	}
   807  	if align < 1 {
   808  		return 1
   809  	}
   810  	return align
   811  }
   812  
   813  func (cfg *ABIConfig) emitAlignDisp4(w io.Writer, reg, base string, off int64) (string, int64) {
   814  	scratch := cfg.TmpReg
   815  	if reg == scratch || base == scratch {
   816  		scratch = cfg.TmpReg2
   817  	}
   818  	cfg.emitAddr(w, base, off, scratch)
   819  	return scratch, 0
   820  }
   821  
   822  // emitScalarLoadInt emits a single power-of-two (1, 2, 4, or 8 byte) integer
   823  // load from off(base) into reg, sign- or zero-extending narrow loads.
   824  func (cfg *ABIConfig) emitScalarLoadInt(w io.Writer, base string, off, size int64, signed bool, reg string) {
   825  	if cfg.asm.alignDisp4 && (size >= 8 || (size == 4 && signed)) && off%4 != 0 {
   826  		base, off = cfg.emitAlignDisp4(w, reg, base, off)
   827  	}
   828  	a := &cfg.asm
   829  	var op string
   830  	switch {
   831  	case size == 1 && signed:
   832  		op = a.loadB
   833  	case size == 1:
   834  		op = a.loadBU
   835  	case size == 2 && signed:
   836  		op = a.loadH
   837  	case size == 2:
   838  		op = a.loadHU
   839  	case size == 4 && signed:
   840  		op = a.loadW
   841  	case size == 4:
   842  		op = a.loadWU
   843  	default:
   844  		op = a.mov
   845  	}
   846  	fmt.Fprintf(w, "\t%s\t%d(%s), %s\n", op, off, base, reg)
   847  }
   848  
   849  // emitScalarStoreInt emits a single power-of-two (1, 2, 4, or 8 byte) integer
   850  // store from reg into off(base).
   851  func (cfg *ABIConfig) emitScalarStoreInt(w io.Writer, reg, base string, off, size int64) {
   852  	if cfg.asm.alignDisp4 && size >= 8 && off%4 != 0 {
   853  		base, off = cfg.emitAlignDisp4(w, reg, base, off)
   854  	}
   855  	a := &cfg.asm
   856  	var op string
   857  	switch size {
   858  	case 1:
   859  		op = a.storeB
   860  	case 2:
   861  		op = a.storeH
   862  	case 4:
   863  		op = a.storeW
   864  	default:
   865  		op = a.mov
   866  	}
   867  	fmt.Fprintf(w, "\t%s\t%s, %d(%s)\n", op, reg, off, base)
   868  }
   869  
   870  func (cfg *ABIConfig) emitShiftOp(w io.Writer, op string, bits int64, reg string) {
   871  	if cfg.asm.twoOpShift {
   872  		fmt.Fprintf(w, "\t%s\t$%d, %s\n", op, bits, reg)
   873  	} else {
   874  		fmt.Fprintf(w, "\t%s\t$%d, %s, %s\n", op, bits, reg, reg)
   875  	}
   876  }
   877  
   878  func (cfg *ABIConfig) emitALUOp(w io.Writer, op, src, dst string) {
   879  	if cfg.asm.twoOpALU {
   880  		fmt.Fprintf(w, "\t%s\t%s, %s\n", op, src, dst)
   881  	} else {
   882  		fmt.Fprintf(w, "\t%s\t%s, %s, %s\n", op, src, dst, dst)
   883  	}
   884  }
   885  
   886  // emitShiftLeft shifts reg left in place by bits.
   887  func (cfg *ABIConfig) emitShiftLeft(w io.Writer, bits int64, reg string) {
   888  	cfg.emitShiftOp(w, cfg.asm.shl, bits, reg)
   889  }
   890  
   891  // emitShiftRight logically shifts reg right in place by bits.
   892  func (cfg *ABIConfig) emitShiftRight(w io.Writer, bits int64, reg string) {
   893  	cfg.emitShiftOp(w, cfg.asm.shr, bits, reg)
   894  }
   895  
   896  // emitOrReg bitwise-ORs src into dst.
   897  func (cfg *ABIConfig) emitOrReg(w io.Writer, src, dst string) {
   898  	cfg.emitALUOp(w, cfg.asm.or, src, dst)
   899  }
   900  
   901  // emitLoadInt loads an integer or struct register chunk of 1..8 bytes from
   902  // off(base) into reg, decomposing non-power-of-two sizes into exact sub-loads
   903  // combined with shifts and ORs.
   904  func (cfg *ABIConfig) emitLoadInt(w io.Writer, base string, off, size int64, signed bool, reg string) {
   905  	cfg.emitLoadIntAlign(w, base, off, size, cfg.PtrSize, signed, reg)
   906  }
   907  
   908  func (cfg *ABIConfig) emitLoadIntAlign(w io.Writer, base string, off, size, align int64, signed bool, reg string) {
   909  	maxWidth := cfg.PtrSize
   910  	if cfg.StrictAlign {
   911  		maxWidth = effAlign(off, align, cfg.PtrSize)
   912  	}
   913  	if (size == 1 || size == 2 || size == 4 || size == 8) && size <= maxWidth {
   914  		cfg.emitScalarLoadInt(w, base, off, size, signed, reg)
   915  		return
   916  	}
   917  	chunks := decomposePow2Aligned(size, maxWidth)
   918  	scratch := cfg.TmpReg2
   919  	if reg == scratch || base == scratch {
   920  		scratch = cfg.TmpReg
   921  	}
   922  	cfg.emitScalarLoadInt(w, base, off, chunks[0], false, reg)
   923  	curOff := chunks[0]
   924  	for _, ck := range chunks[1:] {
   925  		if !cfg.BigEndian {
   926  			cfg.emitScalarLoadInt(w, base, off+curOff, ck, false, scratch)
   927  			cfg.emitShiftLeft(w, curOff*8, scratch)
   928  		} else {
   929  			cfg.emitShiftLeft(w, ck*8, reg)
   930  			cfg.emitScalarLoadInt(w, base, off+curOff, ck, false, scratch)
   931  		}
   932  		cfg.emitOrReg(w, scratch, reg)
   933  		curOff += ck
   934  	}
   935  }
   936  
   937  // emitStoreInt stores an integer or struct register chunk of 1..8 bytes from
   938  // reg into off(base), decomposing non-power-of-two sizes into exact sub-stores.
   939  func (cfg *ABIConfig) emitStoreInt(w io.Writer, reg, base string, off, size int64) {
   940  	cfg.emitStoreIntAlign(w, reg, base, off, size, cfg.PtrSize)
   941  }
   942  
   943  func (cfg *ABIConfig) emitStoreIntAlign(w io.Writer, reg, base string, off, size, align int64) {
   944  	maxWidth := cfg.PtrSize
   945  	if cfg.StrictAlign {
   946  		maxWidth = effAlign(off, align, cfg.PtrSize)
   947  	}
   948  	if (size == 1 || size == 2 || size == 4 || size == 8) && size <= maxWidth {
   949  		cfg.emitScalarStoreInt(w, reg, base, off, size)
   950  		return
   951  	}
   952  	chunks := decomposePow2Aligned(size, maxWidth)
   953  	if !cfg.BigEndian {
   954  		curOff := int64(0)
   955  		for i, ck := range chunks {
   956  			cfg.emitScalarStoreInt(w, reg, base, off+curOff, ck)
   957  			curOff += ck
   958  			if i+1 < len(chunks) {
   959  				cfg.emitShiftRight(w, ck*8, reg)
   960  			}
   961  		}
   962  	} else {
   963  		curOff := size
   964  		for i := len(chunks) - 1; i >= 0; i-- {
   965  			ck := chunks[i]
   966  			curOff -= ck
   967  			cfg.emitScalarStoreInt(w, reg, base, off+curOff, ck)
   968  			if i > 0 {
   969  				cfg.emitShiftRight(w, ck*8, reg)
   970  			}
   971  		}
   972  	}
   973  }
   974  
   975  // emitLoadFloat loads a 4-byte or 8-byte floating-point value from off(base)
   976  // into floating-point register reg.
   977  func (cfg *ABIConfig) emitLoadFloat(w io.Writer, base string, off, size int64, reg string) {
   978  	if cfg.LoadFloat != nil && cfg.LoadFloat(w, base, off, size, reg) {
   979  		return
   980  	}
   981  	op := cfg.asm.fmovD
   982  	if size == 4 {
   983  		op = cfg.asm.fmovS
   984  	}
   985  	fmt.Fprintf(w, "\t%s\t%d(%s), %s\n", op, off, base, reg)
   986  }
   987  
   988  // emitStoreFloat stores a 4-byte or 8-byte floating-point value from
   989  // floating-point register reg into off(base).
   990  func (cfg *ABIConfig) emitStoreFloat(w io.Writer, reg, base string, off, size int64) {
   991  	if cfg.StoreFloat != nil && cfg.StoreFloat(w, reg, base, off, size) {
   992  		return
   993  	}
   994  	op := cfg.asm.fmovD
   995  	if size == 4 {
   996  		op = cfg.asm.fmovS
   997  	}
   998  	fmt.Fprintf(w, "\t%s\t%s, %d(%s)\n", op, reg, off, base)
   999  }
  1000  
  1001  // emitAddr computes the effective address base+off into reg.
  1002  func (cfg *ABIConfig) emitAddr(w io.Writer, base string, off int64, reg string) {
  1003  	if cfg.asm.lea != "" {
  1004  		fmt.Fprintf(w, "\t%s\t%d(%s), %s\n", cfg.asm.lea, off, base, reg)
  1005  		return
  1006  	}
  1007  	fmt.Fprintf(w, "\t%s\t$%d, %s, %s\n", cfg.asm.add, off, base, reg)
  1008  }
  1009  
  1010  // emitMovReg copies pointer-sized register src into dst.
  1011  func (cfg *ABIConfig) emitMovReg(w io.Writer, src, dst string) {
  1012  	fmt.Fprintf(w, "\t%s\t%s, %s\n", cfg.asm.mov, src, dst)
  1013  }
  1014  
  1015  // emitSubReg subtracts register src from dst (dst -= src).
  1016  func (cfg *ABIConfig) emitSubReg(w io.Writer, src, dst string) {
  1017  	cfg.emitALUOp(w, cfg.asm.sub, src, dst)
  1018  }
  1019  
  1020  // emitAddReg adds register src into dst (dst += src).
  1021  func (cfg *ABIConfig) emitAddReg(w io.Writer, src, dst string) {
  1022  	cfg.emitALUOp(w, cfg.asm.add, src, dst)
  1023  }
  1024  
  1025  // emitPPC64AddSP adjusts R1 by delta bytes using signed 16-bit ADD steps so
  1026  // cmd/internal/obj/ppc64 never rewrites large offsets to ADDIS (which drops
  1027  // Spadj tracking, triggers auto-SPWRITE, and can overflow pctospadj) and never
  1028  // uses REGTMP (R31) or REGZERO (R0).
  1029  func emitPPC64AddSP(w io.Writer, delta int64) {
  1030  	if delta < 0 {
  1031  		for rem := -delta; rem > 0; {
  1032  			step := min(rem, 32768)
  1033  			fmt.Fprintf(w, "\tADD\t$-%d, R1\n", step)
  1034  			rem -= step
  1035  		}
  1036  		return
  1037  	}
  1038  	for rem := delta; rem > 0; {
  1039  		step := min(rem, 32752)
  1040  		fmt.Fprintf(w, "\tADD\t$%d, R1\n", step)
  1041  		rem -= step
  1042  	}
  1043  }
  1044  
  1045  // emitPPC64AllocBackchain decrements R1 by size bytes and stores the caller's
  1046  // R1 at 0(R1) as the PowerPC64 ELFv2 / AIX XCOFF stack back-chain pointer,
  1047  // using a single MOVDU when size fits in a signed 16-bit displacement.
  1048  // Otherwise it uses tmpReg to hold the caller's R1.
  1049  func emitPPC64AllocBackchain(w io.Writer, tmpReg string, size int64) {
  1050  	if size <= 32760 {
  1051  		fmt.Fprintf(w, "\tMOVDU\tR1, -%d(R1)\n", size)
  1052  	} else {
  1053  		fmt.Fprintf(w, "\tMOVD\tR1, %s\n", tmpReg)
  1054  		emitPPC64AddSP(w, -size)
  1055  		fmt.Fprintf(w, "\tMOVD\t%s, 0(R1)\n", tmpReg)
  1056  	}
  1057  }
  1058  
  1059  // emitSubSP decrements the architecture stack pointer by size bytes.
  1060  func (cfg *ABIConfig) emitSubSP(w io.Writer, size int64) {
  1061  	if cfg.asm.useAdjSP {
  1062  		fmt.Fprintf(w, "\tADJSP\t$%d\n", size)
  1063  		return
  1064  	}
  1065  	if cfg.asm.negSubSP {
  1066  		fmt.Fprintf(w, "\t%s\t$-%d, %s\n", cfg.asm.add, size, cfg.SPReg)
  1067  		return
  1068  	}
  1069  	fmt.Fprintf(w, "\t%s\t$%d, %s\n", cfg.asm.sub, size, cfg.SPReg)
  1070  }
  1071  
  1072  // emitAddSP increments the architecture stack pointer by size bytes.
  1073  func (cfg *ABIConfig) emitAddSP(w io.Writer, size int64) {
  1074  	if cfg.asm.useAdjSP {
  1075  		fmt.Fprintf(w, "\tADJSP\t$-%d\n", size)
  1076  		return
  1077  	}
  1078  	fmt.Fprintf(w, "\t%s\t$%d, %s\n", cfg.asm.add, size, cfg.SPReg)
  1079  }
  1080  
  1081  // emitLoadStackArg loads a C-caller stack argument at stackOff into reg
  1082  // during a C-to-Go callback trampoline.
  1083  func (cfg *ABIConfig) emitLoadStackArg(w io.Writer, stackOff, callerSPOff, size int64, reg string) {
  1084  	base, off := cfg.SPReg, callerSPOff+stackOff
  1085  	if cfg.StackArgAddr != nil {
  1086  		base, off = cfg.StackArgAddr(stackOff, callerSPOff)
  1087  	}
  1088  	cfg.emitLoadInt(w, base, off, size, false, reg)
  1089  }
  1090  
  1091  // emitCallReg emits an indirect branch-and-link through register reg.
  1092  func (cfg *ABIConfig) emitCallReg(w io.Writer, reg string) {
  1093  	if cfg.asm.lea != "" {
  1094  		fmt.Fprintf(w, "\tCALL\t%s\n", reg)
  1095  	} else if cfg.Arch == "riscv64" {
  1096  		fmt.Fprintf(w, "\tJALR\tX1, (%s)\n", reg)
  1097  	} else {
  1098  		fmt.Fprintf(w, "\tCALL\t(%s)\n", reg)
  1099  	}
  1100  }
  1101  
  1102  // emitCallIndirect calls the C function pointer stored at 0(base).
  1103  func (cfg *ABIConfig) emitCallIndirect(w io.Writer, base string) {
  1104  	if cfg.CallIndirect != nil {
  1105  		cfg.CallIndirect(w, base)
  1106  		return
  1107  	}
  1108  	reg := cmp.Or(cfg.IndCallReg, cfg.TmpReg)
  1109  	cfg.emitLoadInt(w, base, 0, cfg.PtrSize, false, reg)
  1110  	cfg.emitCallReg(w, reg)
  1111  }
  1112  
  1113  // emitCallRuntime emits a direct call to an internal Go runtime helper symbol.
  1114  func (cfg *ABIConfig) emitCallRuntime(w io.Writer, sym string) {
  1115  	if cfg.HasFuncDesc && sym == "_cgo_topofstack" {
  1116  		sym = "__cgo_topofstack"
  1117  	}
  1118  	fmt.Fprintf(w, "\tCALL\t%s(SB)\n", sym)
  1119  	if (cfg.Arch == "ppc64" || cfg.Arch == "ppc64le") && sym != "_cgo_topofstack" && sym != "__cgo_topofstack" {
  1120  		// _cgo_wait_runtime_init_done, crosscall2, and _cgo_release_context
  1121  		// restore host CR via R0 in UNSTACK_AND_RESTORE_GO_TO_HOST_ABI, leaving
  1122  		// R0 non-zero. Re-zero R0 before any subsequent large-constant load or
  1123  		// large-offset addition that assembles to ORI/ORIS with R0.
  1124  		fmt.Fprintf(w, "\tXOR\tR0, R0\n")
  1125  	}
  1126  }
  1127  
  1128  // emitCallSymbol emits a call to external C symbol sym.
  1129  func (cfg *ABIConfig) emitCallSymbol(w io.Writer, sym string, static bool) {
  1130  	if cfg.CallSymbol != nil {
  1131  		cfg.CallSymbol(w, sym, static)
  1132  		return
  1133  	}
  1134  	if cfg.IndirectSymCall && !static {
  1135  		// On PE, a //go:cgo_import_dynamic symbol is a pointer-sized slot
  1136  		// holding the function's address (an IAT entry for internal linking,
  1137  		// or a relocated data word for external linking; see initdynimport
  1138  		// in cmd/link/internal/ld/pe.go). Load the address and call indirectly.
  1139  		reg := cmp.Or(cfg.IndCallReg, cfg.TmpReg)
  1140  		fmt.Fprintf(w, "\t%s\t%s(SB), %s\n", cfg.asm.mov, sym, reg)
  1141  		cfg.emitCallReg(w, reg)
  1142  		return
  1143  	}
  1144  	fmt.Fprintf(w, "\tCALL\t%s(SB)\n", sym)
  1145  }
  1146  
  1147  // emitCopyMem copies size bytes from srcOff(srcBase) to dstOff(dstBase) using
  1148  // alignment-safe power-of-two loads and stores through tmpReg.
  1149  func (cfg *ABIConfig) emitCopyMem(w io.Writer, srcBase string, srcOff int64, dstBase string, dstOff, size, align int64, tmpReg string) {
  1150  	ptrSize := cfg.PtrSize
  1151  	for off := int64(0); off < size; {
  1152  		maxWidth := ptrSize
  1153  		if cfg.StrictAlign {
  1154  			srcA := effAlign(srcOff+off, align, ptrSize)
  1155  			dstA := effAlign(dstOff+off, align, ptrSize)
  1156  			maxWidth = min(srcA, dstA)
  1157  		}
  1158  		chunk := maxPow2Chunk(size-off, maxWidth)
  1159  		cfg.emitScalarLoadInt(w, srcBase, srcOff+off, chunk, false, tmpReg)
  1160  		cfg.emitScalarStoreInt(w, tmpReg, dstBase, dstOff+off, chunk)
  1161  		off += chunk
  1162  	}
  1163  }
  1164  
  1165  // paramRegSlots decomposes register-passed parameter p into per-register
  1166  // load/store descriptors.
  1167  func (cfg *ABIConfig) paramRegSlots(fn BindingFunc, idx int, p ParamLoc, types map[string]BindingType) []regSlot {
  1168  	if len(p.Regs) == 0 {
  1169  		return nil
  1170  	}
  1171  	if p.PassByPtr {
  1172  		return []regSlot{{reg: p.Regs[0], offset: 0, size: cfg.PtrSize, isFloat: false}}
  1173  	}
  1174  	var pt string
  1175  	if paramTypes := fn.Params; idx < len(paramTypes) {
  1176  		pt = paramTypes[idx]
  1177  	}
  1178  	regSize := p.Size - p.StackBytes
  1179  	return cfg.valueRegSlots(pt, regSize, p.IsFloat, p.Regs, types)
  1180  }
  1181  
  1182  // retRegSlots decomposes register-returned result ret into per-register
  1183  // load/store descriptors.
  1184  func (cfg *ABIConfig) retRegSlots(fn BindingFunc, ret RetLoc, types map[string]BindingType) []regSlot {
  1185  	if len(ret.Regs) == 0 || ret.Indirect {
  1186  		return nil
  1187  	}
  1188  	return cfg.valueRegSlots(fn.Ret, ret.Size, ret.IsFloat, ret.Regs, types)
  1189  }
  1190  
  1191  // valueRegSlots maps a value of typeName (with total size and assigned regs)
  1192  // onto individual register pieces, delegating composite register layouts to
  1193  // cfg.CompositeRegSlots when present and otherwise slicing into PtrSize chunks.
  1194  func (cfg *ABIConfig) valueRegSlots(typeName string, size int64, isFloat bool, regs []string, types map[string]BindingType) []regSlot {
  1195  	ptrSize := cfg.PtrSize
  1196  	info := cfg.inspectType(typeName, types)
  1197  	if info.composite && cfg.CompositeRegSlots != nil {
  1198  		if slots, ok := cfg.CompositeRegSlots(cfg, info, isFloat, regs); ok {
  1199  			return slots
  1200  		}
  1201  	}
  1202  	goAlign := min(info.align, ptrSize)
  1203  	if goAlign < 1 {
  1204  		goAlign = 1
  1205  	}
  1206  	slots := make([]regSlot, len(regs))
  1207  	for k, r := range regs {
  1208  		fl := cfg.isFloatReg(r)
  1209  		chunkSz := min(ptrSize, size-int64(k)*ptrSize)
  1210  		if len(regs) == 1 {
  1211  			chunkSz = size
  1212  		}
  1213  		leftJustify := cfg.BigEndian && info.composite && !fl && chunkSz < ptrSize &&
  1214  			(cfg.LeftJustifyBEComposite || (cfg.LeftJustifyBETrailing && info.size > ptrSize))
  1215  		slots[k] = regSlot{
  1216  			reg:         r,
  1217  			offset:      int64(k) * ptrSize,
  1218  			size:        chunkSz,
  1219  			align:       goAlign,
  1220  			isFloat:     fl,
  1221  			signed:      !info.composite && !fl && (info.signed || (cfg.SignExtUint32 && chunkSz == 4)),
  1222  			leftJustify: leftJustify,
  1223  		}
  1224  	}
  1225  	return slots
  1226  }
  1227  
  1228  func (cfg *ABIConfig) goTypeAlign(typeName string, types map[string]BindingType) int64 {
  1229  	if typeName == "" {
  1230  		return 1
  1231  	}
  1232  	a := min(cfg.inspectType(typeName, types).align, cfg.PtrSize)
  1233  	if a < 1 {
  1234  		return 1
  1235  	}
  1236  	return a
  1237  }
  1238  
  1239  func (cfg *ABIConfig) paramTypeInfo(fn BindingFunc, idx int, types map[string]BindingType) typeInfo {
  1240  	var pt string
  1241  	if paramTypes := fn.Params; idx < len(paramTypes) {
  1242  		pt = paramTypes[idx]
  1243  	}
  1244  	return cfg.inspectType(pt, types)
  1245  }
  1246  
  1247  // emitLoadSlot loads a single register piece from off+slot.offset(base) into slot.reg.
  1248  func (cfg *ABIConfig) emitLoadSlot(w io.Writer, base string, off int64, slot regSlot) {
  1249  	if slot.isFloat {
  1250  		cfg.emitLoadFloat(w, base, off+slot.offset, slot.size, slot.reg)
  1251  		return
  1252  	}
  1253  	cfg.emitLoadIntAlign(w, base, off+slot.offset, slot.size, slot.align, slot.signed, slot.reg)
  1254  	if slot.leftJustify {
  1255  		cfg.emitShiftLeft(w, (cfg.PtrSize-slot.size)*8, slot.reg)
  1256  	}
  1257  }
  1258  
  1259  // emitStoreSlot stores a register piece into off+slot.offset(base).
  1260  func (cfg *ABIConfig) emitStoreSlot(w io.Writer, slot regSlot, base string, off int64) {
  1261  	if slot.isFloat {
  1262  		cfg.emitStoreFloat(w, slot.reg, base, off+slot.offset, slot.size)
  1263  		return
  1264  	}
  1265  	if slot.leftJustify {
  1266  		cfg.emitShiftRight(w, (cfg.PtrSize-slot.size)*8, slot.reg)
  1267  	}
  1268  	cfg.emitStoreIntAlign(w, slot.reg, base, off+slot.offset, slot.size, slot.align)
  1269  }
  1270  
  1271  // complexFloatStackPad returns the byte offset of each float32 half of a
  1272  // complex64 stack argument within its PtrSize slot when
  1273  // ComplexFloatSplitStack is set.
  1274  func (cfg *ABIConfig) complexFloatStackPad() int64 {
  1275  	if cfg.BigEndian && !cfg.LeftJustifyBEFloatStack {
  1276  		return cfg.PtrSize - 4
  1277  	}
  1278  	return 0
  1279  }
  1280  
  1281  // emitRISCTrampolinePrologue emits a NOFRAME Go-to-C trampoline prologue for
  1282  // link-register architectures and returns its matching epilogue. When 0(SP) is
  1283  // not occupied by C stack arguments or C ABI shadow space, it stores LinkReg at
  1284  // 0(SP) using Go's three-instruction sequence (store at -total(SP), decrement
  1285  // SP, re-store at 0(SP)) so Go traceback and .debug_frame unwinding see saved
  1286  // LR at 0(SP) with no window.
  1287  func (cfg *ABIConfig) emitRISCTrampolinePrologue(w io.Writer, lay FuncLayout) func(io.Writer) {
  1288  	ptrSize := cfg.PtrSize
  1289  	lrAtZero := !cfg.ShadowUsesSlot0 && (cfg.ShadowSpace > 0 || !lay.hasStackArgs())
  1290  	if lrAtZero {
  1291  		total := max(cfg.LRReserve, lay.StackSize)
  1292  		cfg.emitStoreInt(w, cfg.LinkReg, cfg.SPReg, -total, ptrSize)
  1293  		cfg.emitSubSP(w, total)
  1294  		cfg.emitStoreInt(w, cfg.LinkReg, cfg.SPReg, 0, ptrSize)
  1295  		cfg.emitMovReg(w, cfg.IntRegs[0], cfg.CalleeSavedReg)
  1296  		return func(w io.Writer) {
  1297  			cfg.emitLoadInt(w, cfg.SPReg, 0, ptrSize, false, cfg.LinkReg)
  1298  			cfg.emitAddSP(w, total)
  1299  		}
  1300  	}
  1301  	total := lay.StackSize + cfg.StackAlign
  1302  	lrOff := total - ptrSize
  1303  	cfg.emitSubSP(w, total)
  1304  	cfg.emitStoreInt(w, cfg.LinkReg, cfg.SPReg, lrOff, ptrSize)
  1305  	cfg.emitMovReg(w, cfg.IntRegs[0], cfg.CalleeSavedReg)
  1306  	return func(w io.Writer) {
  1307  		cfg.emitLoadInt(w, cfg.SPReg, lrOff, ptrSize, false, cfg.LinkReg)
  1308  		cfg.emitAddSP(w, total)
  1309  	}
  1310  }
  1311  
  1312  // emitRISCCallbackPrologue saves AsmTmpReg (if any) and LinkReg on the stack
  1313  // and allocates LocalFrameOff+frameSize bytes for writeCallbackTrampoline.
  1314  func (cfg *ABIConfig) emitRISCCallbackPrologue(w io.Writer, frameSize int64) int64 {
  1315  	ptrSize := cfg.PtrSize
  1316  	inner := cfg.LocalFrameOff + frameSize
  1317  	if cfg.AsmTmpReg == "" || inner <= 2032 {
  1318  		if cfg.ShadowSpace == 0 {
  1319  			cfg.emitStoreInt(w, cfg.LinkReg, cfg.SPReg, -inner, ptrSize)
  1320  		}
  1321  		cfg.emitSubSP(w, inner)
  1322  		cfg.emitStoreInt(w, cfg.LinkReg, cfg.SPReg, cfg.ShadowSpace, ptrSize)
  1323  		if cfg.AsmTmpReg != "" {
  1324  			cfg.emitStoreInt(w, cfg.AsmTmpReg, cfg.SPReg, cfg.ShadowSpace+ptrSize, ptrSize)
  1325  		}
  1326  		return inner
  1327  	}
  1328  	outer := cfg.StackAlign
  1329  	cfg.emitSubSP(w, outer)
  1330  	cfg.emitStoreInt(w, cfg.AsmTmpReg, cfg.SPReg, 0, ptrSize)
  1331  	if cfg.ShadowSpace == 0 {
  1332  		cfg.emitStoreInt(w, cfg.LinkReg, cfg.SPReg, -inner, ptrSize)
  1333  	}
  1334  	cfg.emitSubSP(w, inner)
  1335  	cfg.emitStoreInt(w, cfg.LinkReg, cfg.SPReg, cfg.ShadowSpace, ptrSize)
  1336  	return outer + inner
  1337  }
  1338  
  1339  // emitRISCCallbackEpilogue restores LinkReg, AsmTmpReg, and SPReg and returns.
  1340  func (cfg *ABIConfig) emitRISCCallbackEpilogue(w io.Writer, frameSize int64) {
  1341  	ptrSize := cfg.PtrSize
  1342  	inner := cfg.LocalFrameOff + frameSize
  1343  	if cfg.AsmTmpReg == "" || inner <= 2032 {
  1344  		if cfg.AsmTmpReg != "" {
  1345  			cfg.emitLoadInt(w, cfg.SPReg, cfg.ShadowSpace+ptrSize, ptrSize, false, cfg.AsmTmpReg)
  1346  		}
  1347  		cfg.emitLoadInt(w, cfg.SPReg, cfg.ShadowSpace, ptrSize, false, cfg.LinkReg)
  1348  		cfg.emitAddSP(w, inner)
  1349  		fmt.Fprintf(w, "\tRET\n")
  1350  		return
  1351  	}
  1352  	cfg.emitLoadInt(w, cfg.SPReg, cfg.ShadowSpace, ptrSize, false, cfg.LinkReg)
  1353  	cfg.emitAddSP(w, inner)
  1354  	cfg.emitLoadInt(w, cfg.SPReg, 0, ptrSize, false, cfg.AsmTmpReg)
  1355  	cfg.emitAddSP(w, cfg.StackAlign)
  1356  	fmt.Fprintf(w, "\tRET\n")
  1357  }
  1358  
  1359  // emitTextHeader emits the TEXT directive for sym (wrapped in an XCOFF
  1360  // function descriptor when cfg.HasFuncDesc is set).
  1361  func (cfg *ABIConfig) emitTextHeader(w io.Writer, sym, flags string) {
  1362  	if cfg.HasFuncDesc {
  1363  		textSym := sym + "_text<>"
  1364  		fmt.Fprintf(w, "DATA %s+0(SB)/8, $%s(SB)\n", sym, textSym)
  1365  		fmt.Fprintf(w, "DATA %s+8(SB)/8, $TOC(SB)\n", sym)
  1366  		fmt.Fprintf(w, "DATA %s+16(SB)/8, $0\n", sym)
  1367  		fmt.Fprintf(w, "GLOBL %s(SB), NOPTR, $24\n", sym)
  1368  		fmt.Fprintf(w, "TEXT %s(SB), %s, $0-0\n", textSym, flags)
  1369  		return
  1370  	}
  1371  	fmt.Fprintf(w, "TEXT %s(SB), %s, $0-0\n", sym, flags)
  1372  }
  1373  
  1374  // emitCallCrosscall2 emits the shared register-ABI callback sequence:
  1375  // _cgo_wait_runtime_init_done -> crosscall2(fn, &frame, frameSize, ctxt) -> _cgo_release_context.
  1376  func (cfg *ABIConfig) emitCallCrosscall2(w io.Writer, fnName string, frameSize, ctxtOff, fnDescOff int64) {
  1377  	if cfg.CallCrosscall2 != nil {
  1378  		cfg.CallCrosscall2(w, fnName, frameSize, ctxtOff)
  1379  		return
  1380  	}
  1381  	ptrSize := cfg.PtrSize
  1382  	arg0, arg1, arg2, arg3 := cfg.IntRegs[0], cfg.IntRegs[1], cfg.IntRegs[2], cfg.IntRegs[3]
  1383  	ret0 := cfg.IntRetRegs[0]
  1384  	cfg.emitCallRuntime(w, "_cgo_wait_runtime_init_done")
  1385  	cfg.emitStoreInt(w, ret0, cfg.SPReg, ctxtOff, ptrSize)
  1386  	cfg.emitMovReg(w, ret0, arg3)
  1387  	if cfg.Arch == "arm" {
  1388  		// Use MOVW $sym + double load so -dynlink GOT rewrites load directly into
  1389  		// arg0 without clobbering C callee-saved R9.
  1390  		fmt.Fprintf(w, "\tMOVW\t$·_cgo_fn_%s(SB), %s\n", fnName, arg0)
  1391  		fmt.Fprintf(w, "\tMOVW\t0(%s), %s\n", arg0, arg0)
  1392  		fmt.Fprintf(w, "\tMOVW\t0(%s), %s\n", arg0, arg0)
  1393  	} else if cfg.Arch == "amd64" {
  1394  		// Use LEAQ + double load so -dynlink GOT rewrites do not clobber C callee-saved R15.
  1395  		fmt.Fprintf(w, "\tLEAQ\t·_cgo_fn_%s(SB), %s\n", fnName, arg0)
  1396  		fmt.Fprintf(w, "\tMOVQ\t0(%s), %s\n", arg0, arg0)
  1397  		fmt.Fprintf(w, "\tMOVQ\t0(%s), %s\n", arg0, arg0)
  1398  	} else if cfg.HasFuncDesc {
  1399  		fmt.Fprintf(w, "\tMOVD\t·_cgo_fn_%s(SB), %s\n", fnName, arg0)
  1400  		fmt.Fprintf(w, "\tMOVD\t0(%s), %s\n", arg0, arg0)
  1401  		cfg.emitStoreInt(w, arg0, cfg.SPReg, fnDescOff, 8)
  1402  		cfg.emitStoreInt(w, "R2", cfg.SPReg, fnDescOff+8, 8)
  1403  		cfg.emitAddr(w, cfg.SPReg, fnDescOff, arg0)
  1404  	} else {
  1405  		fmt.Fprintf(w, "\t%s\t·_cgo_fn_%s(SB), %s\n", cfg.asm.mov, fnName, arg0)
  1406  		cfg.emitLoadInt(w, arg0, 0, ptrSize, false, arg0)
  1407  	}
  1408  	cfg.emitAddr(w, cfg.SPReg, cfg.LocalFrameOff, arg1)
  1409  	fmt.Fprintf(w, "\t%s\t$%d, %s\n", cfg.asm.mov, frameSize, arg2)
  1410  	cfg.emitCallRuntime(w, "crosscall2")
  1411  	cfg.emitLoadInt(w, cfg.SPReg, ctxtOff, ptrSize, false, arg0)
  1412  	cfg.emitCallRuntime(w, "_cgo_release_context")
  1413  }
  1414  
  1415  // writeTrampoline emits the Go-to-C assembly trampoline for fn.
  1416  // Go callers pack parameters into a _cgo_arg_<Name> struct and pass its address
  1417  // to runtime.cgocall, which enters a syscall, switches to the OS-allocated g0
  1418  // system stack via asmcgocall, and invokes this trampoline using the platform C
  1419  // ABI for void fn(void *arg) (passing the struct pointer in IntRegs[0], or
  1420  // 0(SP) on 386). The trampoline unpacks arguments into C ABI registers and
  1421  // stack slots, calls the target C function, and writes any result back to the
  1422  // _cgo_arg_<Name> struct.
  1423  func (cfg *ABIConfig) writeTrampoline(w io.Writer, fn BindingFunc, types map[string]BindingType) {
  1424  	ptrSize := cfg.PtrSize
  1425  	lay := cfg.layout(fn, types)
  1426  
  1427  	trampSym := fmt.Sprintf("_cgo%s_trampoline_%s", cPrefix, fn.Name)
  1428  	var epilogue func(io.Writer)
  1429  	if cfg.TrampolinePrologue != nil {
  1430  		cfg.emitTextHeader(w, trampSym, "NOSPLIT|NOFRAME")
  1431  		epilogue = cfg.TrampolinePrologue(w, lay)
  1432  	} else if cfg.LinkReg != "" {
  1433  		cfg.emitTextHeader(w, trampSym, "NOSPLIT|NOFRAME")
  1434  		epilogue = cfg.emitRISCTrampolinePrologue(w, lay)
  1435  	} else {
  1436  		cfg.emitTextHeader(w, trampSym, "NOSPLIT")
  1437  		// Hold the _cgo_arg struct pointer in CalleeSavedReg across the C call:
  1438  		// the C callee preserves it per the C ABI, and our caller (runtime.asmcgocall)
  1439  		// does not keep a live value in CalleeSavedReg, so we need not save/restore it.
  1440  		if cfg.Prologue != nil {
  1441  			epilogue = cfg.Prologue(w)
  1442  		} else {
  1443  			cfg.emitMovReg(w, cfg.IntRegs[0], cfg.CalleeSavedReg)
  1444  		}
  1445  
  1446  		if lay.StackSize > 0 {
  1447  			cfg.emitSubSP(w, lay.StackSize)
  1448  		}
  1449  	}
  1450  
  1451  	base := cfg.CalleeSavedReg
  1452  
  1453  	if fn.MayCallback {
  1454  		if fn.Ret != "" && lay.Ret.Size > 0 {
  1455  			cfg.emitCallRuntime(w, "_cgo_topofstack")
  1456  			cfg.emitStoreInt(w, cfg.IntRetRegs[0], cfg.SPReg, lay.StkTopOff, ptrSize)
  1457  		}
  1458  		for i, p := range lay.Params {
  1459  			if p.PassByPtr {
  1460  				pAlign := min(cfg.paramTypeInfo(fn, i, types).align, ptrSize)
  1461  				cfg.emitCopyMem(w, base, p.GoOffset, cfg.SPReg, p.G0Off, p.Size, pAlign, cfg.TmpReg)
  1462  			}
  1463  		}
  1464  	}
  1465  
  1466  	if lay.Ret.Indirect {
  1467  		retBase, retOff := base, lay.Ret.GoOffset
  1468  		if fn.MayCallback {
  1469  			retBase, retOff = cfg.SPReg, lay.Ret.G0Off
  1470  		}
  1471  		if lay.Ret.IndirectOnStack {
  1472  			cfg.emitAddr(w, retBase, retOff, cfg.TmpReg)
  1473  			cfg.emitStoreInt(w, cfg.TmpReg, cfg.SPReg, 0, ptrSize)
  1474  		} else {
  1475  			cfg.emitAddr(w, retBase, retOff, cfg.IndirectRetReg)
  1476  		}
  1477  	}
  1478  
  1479  	for i, p := range lay.Params {
  1480  		srcBase, srcOff := base, p.GoOffset
  1481  		if fn.MayCallback && p.PassByPtr {
  1482  			srcBase, srcOff = cfg.SPReg, p.G0Off
  1483  		}
  1484  		if p.PassByPtr {
  1485  			if len(p.Regs) > 0 {
  1486  				cfg.emitAddr(w, srcBase, srcOff, p.Regs[0])
  1487  			} else {
  1488  				cfg.emitAddr(w, srcBase, srcOff, cfg.TmpReg)
  1489  				cfg.emitStoreInt(w, cfg.TmpReg, cfg.SPReg, p.StackOff, ptrSize)
  1490  			}
  1491  			continue
  1492  		}
  1493  		info := cfg.paramTypeInfo(fn, i, types)
  1494  		pAlign := min(info.align, ptrSize)
  1495  		if slots := cfg.paramRegSlots(fn, i, p, types); len(slots) > 0 {
  1496  			for _, slot := range slots {
  1497  				cfg.emitLoadSlot(w, srcBase, srcOff, slot)
  1498  			}
  1499  			if p.StackBytes > 0 {
  1500  				regBytes := p.Size - p.StackBytes
  1501  				cfg.emitCopyMem(w, srcBase, srcOff+regBytes, cfg.SPReg, p.StackOff, p.StackBytes, pAlign, cfg.TmpReg)
  1502  			}
  1503  			continue
  1504  		}
  1505  		if cfg.ComplexFloatSplitStack && info.isComplex && p.Size == 8 {
  1506  			// The float32 halves of a complex64 occupy separate stack slots.
  1507  			pad := cfg.complexFloatStackPad()
  1508  			cfg.emitCopyMem(w, srcBase, srcOff, cfg.SPReg, p.StackOff+pad, 4, pAlign, cfg.TmpReg)
  1509  			cfg.emitCopyMem(w, srcBase, srcOff+4, cfg.SPReg, p.StackOff+ptrSize+pad, 4, pAlign, cfg.TmpReg)
  1510  			continue
  1511  		}
  1512  		if (!info.composite || cfg.RightJustifyBECompositeStack) && (p.Size == 1 || p.Size == 2 || p.Size == 4 || p.Size == 8) && p.Size <= ptrSize {
  1513  			signed := !info.composite && !info.isFloat && (info.signed || (cfg.SignExtUint32 && p.Size == 4))
  1514  			cfg.emitLoadIntAlign(w, srcBase, srcOff, p.Size, pAlign, signed, cfg.TmpReg)
  1515  			storeSize := ptrSize
  1516  			if cfg.PackStackArgs || (cfg.LeftJustifyBEFloatStack && info.isFloat) {
  1517  				storeSize = p.Size
  1518  			}
  1519  			cfg.emitStoreInt(w, cfg.TmpReg, cfg.SPReg, p.StackOff, storeSize)
  1520  			continue
  1521  		}
  1522  		dstStackOff := p.StackOff
  1523  		if cfg.BigEndian && cfg.RightJustifyBECompositeStack && info.composite && p.Size < ptrSize {
  1524  			dstStackOff += ptrSize - p.Size
  1525  		}
  1526  		cfg.emitCopyMem(w, srcBase, srcOff, cfg.SPReg, dstStackOff, p.Size, pAlign, cfg.TmpReg)
  1527  	}
  1528  
  1529  	if cfg.PreCall != nil {
  1530  		cfg.PreCall(cfg, w, fn, lay)
  1531  	}
  1532  
  1533  	switch {
  1534  	case fn.Indirect:
  1535  		cfg.emitCallIndirect(w, base)
  1536  	case fn.CName == "":
  1537  		panic("BindingFunc.CName must be set")
  1538  	default:
  1539  		cfg.emitCallSymbol(w, fn.CName, fn.Static)
  1540  	}
  1541  	if lay.Ret.IndirectOnStack && cfg.SysVI386SretPop {
  1542  		// The C callee returned with RET $4, popping the 4-byte sret slot
  1543  		// without obj6's deltasp tracking it. Emit SUBL rather than ADJSP so
  1544  		// SP is restored without unbalancing deltasp.
  1545  		fmt.Fprintf(w, "\tSUBL\t$4, SP\n")
  1546  	}
  1547  
  1548  	if fn.Ret != "" && lay.Ret.Size > 0 {
  1549  		retDstBase, retDstOff := base, lay.Ret.GoOffset
  1550  		if fn.MayCallback {
  1551  			retDstBase, retDstOff = cfg.SPReg, lay.Ret.G0Off
  1552  		}
  1553  		if !lay.Ret.Indirect {
  1554  			for _, slot := range cfg.retRegSlots(fn, lay.Ret, types) {
  1555  				cfg.emitStoreSlot(w, slot, retDstBase, retDstOff)
  1556  			}
  1557  		}
  1558  		if fn.MayCallback {
  1559  			cfg.emitCallRuntime(w, "_cgo_topofstack")
  1560  			cfg.emitLoadInt(w, cfg.SPReg, lay.StkTopOff, ptrSize, false, cfg.TmpReg)
  1561  			cfg.emitSubReg(w, cfg.TmpReg, cfg.IntRetRegs[0])
  1562  			cfg.emitAddReg(w, cfg.IntRetRegs[0], base)
  1563  			cfg.emitCopyMem(w, cfg.SPReg, lay.Ret.G0Off, base, lay.Ret.GoOffset, lay.Ret.Size, cfg.goTypeAlign(fn.Ret, types), cfg.TmpReg)
  1564  		}
  1565  	}
  1566  
  1567  	if cfg.TrampolinePrologue == nil && cfg.LinkReg == "" && lay.StackSize > 0 {
  1568  		cfg.emitAddSP(w, lay.StackSize)
  1569  	}
  1570  	if epilogue != nil {
  1571  		epilogue(w)
  1572  	}
  1573  	fmt.Fprintf(w, "\tRET\n\n")
  1574  }
  1575  
  1576  // writeCallbackTrampoline emits the C-callable export trampoline for an
  1577  // //export Go function. It spills C ABI register and stack arguments into a
  1578  // packed Go argument struct on the C stack, invokes Go via crosscall2, and
  1579  // loads the return value into C ABI return registers or the sret buffer.
  1580  func (cfg *ABIConfig) writeCallbackTrampoline(w io.Writer, fn BindingFunc, types map[string]BindingType) {
  1581  	lay := cfg.layout(fn, types)
  1582  	ptrSize := cfg.PtrSize
  1583  
  1584  	structSize := ptrSize
  1585  	if fn.Ret != "" {
  1586  		structSize = lay.Ret.GoOffset + lay.Ret.Size
  1587  	} else if len(lay.Params) > 0 {
  1588  		last := lay.Params[len(lay.Params)-1]
  1589  		structSize = last.GoOffset + last.Size
  1590  	}
  1591  	retBufOff := int64(-1)
  1592  	if lay.Ret.Indirect {
  1593  		retBufOff = alignUp(structSize, ptrSize)
  1594  		structSize = retBufOff + ptrSize
  1595  	}
  1596  	ctxtOff := alignUp(structSize, ptrSize)
  1597  	structSize = ctxtOff + ptrSize
  1598  	fnDescOff := int64(-1)
  1599  	if cfg.HasFuncDesc {
  1600  		fnDescOff = alignUp(structSize, ptrSize)
  1601  		structSize = fnDescOff + 16
  1602  	}
  1603  	frameSize := max(16, alignUp(structSize, 16))
  1604  
  1605  	var callerSPOff int64
  1606  	switch {
  1607  	case cfg.CallbackPrologue != nil:
  1608  		cfg.emitTextHeader(w, fn.Name, "NOSPLIT|NOFRAME")
  1609  		callerSPOff = cfg.CallbackPrologue(w, frameSize)
  1610  	case cfg.LinkReg != "":
  1611  		fmt.Fprintf(w, "TEXT %s(SB), NOSPLIT|NOFRAME, $0-0\n", fn.Name)
  1612  		callerSPOff = cfg.emitRISCCallbackPrologue(w, frameSize)
  1613  	default:
  1614  		totalFrame := cfg.LocalFrameOff + frameSize
  1615  		fmt.Fprintf(w, "TEXT %s(SB), NOSPLIT, $%d-0\n", fn.Name, totalFrame)
  1616  		callerSPOff = totalFrame
  1617  	}
  1618  
  1619  	baseOff := cfg.LocalFrameOff
  1620  
  1621  	if lay.Ret.Indirect {
  1622  		if lay.Ret.IndirectOnStack {
  1623  			cfg.emitLoadStackArg(w, 0, callerSPOff, ptrSize, cfg.TmpReg)
  1624  			cfg.emitStoreInt(w, cfg.TmpReg, cfg.SPReg, baseOff+retBufOff, ptrSize)
  1625  		} else {
  1626  			cfg.emitStoreInt(w, cfg.IndirectRetReg, cfg.SPReg, baseOff+retBufOff, ptrSize)
  1627  		}
  1628  	}
  1629  
  1630  	for i, p := range lay.Params {
  1631  		info := cfg.paramTypeInfo(fn, i, types)
  1632  		pAlign := min(info.align, ptrSize)
  1633  		slots := cfg.paramRegSlots(fn, i, p, types)
  1634  
  1635  		if p.PassByPtr {
  1636  			ptrReg := cfg.TmpReg
  1637  			copyReg := cfg.TmpReg2
  1638  			if len(slots) > 0 {
  1639  				ptrReg = slots[0].reg
  1640  				copyReg = cfg.TmpReg
  1641  			} else {
  1642  				cfg.emitLoadStackArg(w, p.StackOff, callerSPOff, ptrSize, ptrReg)
  1643  			}
  1644  			cfg.emitCopyMem(w, ptrReg, 0, cfg.SPReg, baseOff+p.GoOffset, p.Size, pAlign, copyReg)
  1645  		} else if len(slots) > 0 {
  1646  			for _, slot := range slots {
  1647  				cfg.emitStoreSlot(w, slot, cfg.SPReg, baseOff+p.GoOffset)
  1648  			}
  1649  			if p.StackBytes > 0 {
  1650  				regBytes := p.Size - p.StackBytes
  1651  				srcBase, srcOff := cfg.SPReg, callerSPOff+p.StackOff
  1652  				if cfg.StackArgAddr != nil {
  1653  					srcBase, srcOff = cfg.StackArgAddr(p.StackOff, callerSPOff)
  1654  				}
  1655  				cfg.emitCopyMem(w, srcBase, srcOff, cfg.SPReg, baseOff+p.GoOffset+regBytes, p.StackBytes, pAlign, cfg.TmpReg)
  1656  			}
  1657  		} else if cfg.ComplexFloatSplitStack && info.isComplex && p.Size == 8 {
  1658  			// The float32 halves of a complex64 occupy separate stack slots.
  1659  			pad := cfg.complexFloatStackPad()
  1660  			for k := range int64(2) {
  1661  				srcBase, srcOff := cfg.SPReg, callerSPOff+p.StackOff+k*ptrSize+pad
  1662  				if cfg.StackArgAddr != nil {
  1663  					srcBase, srcOff = cfg.StackArgAddr(p.StackOff+k*ptrSize+pad, callerSPOff)
  1664  				}
  1665  				cfg.emitCopyMem(w, srcBase, srcOff, cfg.SPReg, baseOff+p.GoOffset+k*4, 4, pAlign, cfg.TmpReg)
  1666  			}
  1667  		} else {
  1668  			srcStackOff := p.StackOff
  1669  			if cfg.BigEndian && p.Size < ptrSize && (!info.composite || cfg.RightJustifyBECompositeStack) &&
  1670  				!(cfg.LeftJustifyBEFloatStack && info.isFloat) {
  1671  				srcStackOff += ptrSize - p.Size
  1672  			}
  1673  			srcBase, srcOff := cfg.SPReg, callerSPOff+srcStackOff
  1674  			if cfg.StackArgAddr != nil {
  1675  				srcBase, srcOff = cfg.StackArgAddr(srcStackOff, callerSPOff)
  1676  			}
  1677  			cfg.emitCopyMem(w, srcBase, srcOff, cfg.SPReg, baseOff+p.GoOffset, p.Size, pAlign, cfg.TmpReg)
  1678  		}
  1679  	}
  1680  
  1681  	// Zero pointer-containing return slots on the C stack so Go GC write
  1682  	// barriers in _cgoexp_* never observe uninitialized stack bytes.
  1683  	if fn.Ret != "" && lay.Ret.Size > 0 && cfg.inspectType(fn.Ret, types).hasPointers {
  1684  		zeroSrc := cfg.ZeroVal
  1685  		if zeroSrc == "" {
  1686  			fmt.Fprintf(w, "\t%s\t$0, %s\n", cfg.asm.mov, cfg.TmpReg)
  1687  			zeroSrc = cfg.TmpReg
  1688  		}
  1689  		for off := int64(0); off < lay.Ret.Size; {
  1690  			sz := maxPow2Chunk(lay.Ret.Size-off, ptrSize)
  1691  			cfg.emitStoreInt(w, zeroSrc, cfg.SPReg, baseOff+lay.Ret.GoOffset+off, sz)
  1692  			off += sz
  1693  		}
  1694  	}
  1695  
  1696  	cfg.emitCallCrosscall2(w, fn.Name, frameSize, baseOff+ctxtOff, baseOff+fnDescOff)
  1697  
  1698  	if fn.Ret != "" {
  1699  		if lay.Ret.Indirect {
  1700  			bufReg := cfg.TmpReg
  1701  			copyReg := cfg.TmpReg2
  1702  			if (cfg.IndirectRetInArg || lay.Ret.IndirectOnStack) && len(cfg.IntRetRegs) > 0 {
  1703  				bufReg = cfg.IntRetRegs[0]
  1704  				copyReg = cfg.TmpReg
  1705  			}
  1706  			cfg.emitLoadInt(w, cfg.SPReg, baseOff+retBufOff, ptrSize, false, bufReg)
  1707  			cfg.emitCopyMem(w, cfg.SPReg, baseOff+lay.Ret.GoOffset, bufReg, 0, lay.Ret.Size, cfg.goTypeAlign(fn.Ret, types), copyReg)
  1708  		} else {
  1709  			for _, slot := range cfg.retRegSlots(fn, lay.Ret, types) {
  1710  				cfg.emitLoadSlot(w, cfg.SPReg, baseOff+lay.Ret.GoOffset, slot)
  1711  			}
  1712  		}
  1713  	}
  1714  
  1715  	switch {
  1716  	case cfg.CallbackEpilogue != nil:
  1717  		cfg.CallbackEpilogue(w, frameSize, lay.Ret.IndirectOnStack && cfg.SysVI386SretPop)
  1718  		fmt.Fprintf(w, "\n")
  1719  	case cfg.LinkReg != "":
  1720  		cfg.emitRISCCallbackEpilogue(w, frameSize)
  1721  		fmt.Fprintf(w, "\n")
  1722  	default:
  1723  		fmt.Fprintf(w, "\tRET\n\n")
  1724  	}
  1725  }
  1726  
  1727  // System V AMD64 C calling convention (used on Linux, macOS/iOS, Android,
  1728  // Solaris/Illumos, and the BSDs).
  1729  //
  1730  // Specification: "System V Application Binary Interface: AMD64 Architecture
  1731  // Processor Supplement", Section 3.2 ("Function Calling Sequence"),
  1732  // https://gitlab.com/x86-psABIs/x86-64-ABI.
  1733  //
  1734  // Summary:
  1735  //   - Integer and pointer arguments use DI, SI, DX, CX, R8, R9; floating-point
  1736  //     arguments use X0..X7 (Section 3.2.3, Figure 3.4).
  1737  //   - Aggregates up to 16 bytes with naturally aligned fields are partitioned
  1738  //     into one or two 8-byte "eightbytes", each classified as SSE (all
  1739  //     float/double leaves) or INTEGER (any integer/pointer leaf); all
  1740  //     eightbytes of an aggregate must fit in remaining registers or the entire
  1741  //     aggregate spills to an 8-byte-aligned stack slot without consuming
  1742  //     registers (Section 3.2.3, "Aggregate and Union Arguments").
  1743  //   - Aggregates larger than 16 bytes or containing unaligned fields have class
  1744  //     MEMORY: passed on the stack, and returned via a hidden sret buffer
  1745  //     pointer in DI (consuming the first integer argument register) echoed in AX.
  1746  //   - Scalar and register-classified aggregate results use AX, DX and/or X0, X1
  1747  //     (Section 3.2.3, "Returning of Values").
  1748  //   - The stack frame is 16-byte aligned before CALL, and AL holds an upper
  1749  //     bound (0..8) on the number of XMM registers used in variadic calls
  1750  //     (Sections 3.2.2 and 3.5.7).
  1751  
  1752  // sysVEightbyte describes the register class and transfer width of one 8-byte
  1753  // slice of a System V AMD64 aggregate (SysV AMD64 psABI Section 3.2.3).
  1754  type sysVEightbyte struct {
  1755  	isFloat bool
  1756  	size    int64
  1757  }
  1758  
  1759  // classifySysVStruct classifies a composite type of up to 16 bytes into one or
  1760  // two System V AMD64 eightbytes (SSE vs INTEGER) per SysV AMD64 psABI
  1761  // Section 3.2.3 ("Parameter Passing"). It returns ok=false if the aggregate
  1762  // exceeds 16 bytes or contains unaligned fields, requiring MEMORY placement.
  1763  func classifySysVStruct(info typeInfo) ([]sysVEightbyte, bool) {
  1764  	size := info.size
  1765  	if size <= 0 || size > 16 {
  1766  		return nil, false
  1767  	}
  1768  	var hasFloat, hasInt [2]bool
  1769  	var maxEnd [2]int64
  1770  	if info.fieldsOK {
  1771  		for _, f := range info.fields {
  1772  			if f.size <= 0 {
  1773  				continue
  1774  			}
  1775  			eb := f.offset / 8
  1776  			if (f.align > 1 && f.offset%f.align != 0) || eb >= 2 || (f.offset+f.size-1)/8 != eb {
  1777  				return nil, false
  1778  			}
  1779  			maxEnd[eb] = max(maxEnd[eb], f.offset%8+f.size)
  1780  			if f.isFloat {
  1781  				hasFloat[eb] = true
  1782  				continue
  1783  			}
  1784  			hasInt[eb] = true
  1785  		}
  1786  	}
  1787  
  1788  	ebCount := (size + 7) / 8
  1789  	out := make([]sysVEightbyte, ebCount)
  1790  	for k := range ebCount {
  1791  		if hasFloat[k] && !hasInt[k] {
  1792  			sz := int64(8)
  1793  			if maxEnd[k] <= 4 {
  1794  				sz = 4
  1795  			}
  1796  			out[k] = sysVEightbyte{isFloat: true, size: sz}
  1797  			continue
  1798  		}
  1799  		out[k] = sysVEightbyte{size: min(8, size-k*8)}
  1800  	}
  1801  	return out, true
  1802  }
  1803  
  1804  // assignSysVRegs allocates integer and SSE registers for ebs from intRegs and
  1805  // floatRegs starting at *intIdx and *floatIdx, advancing the cursors only when
  1806  // all eightbytes fit in registers (SysV AMD64 psABI Section 3.2.3).
  1807  func assignSysVRegs(ebs []sysVEightbyte, intRegs, floatRegs []string, intIdx, floatIdx *int) (regs []string, allFloat, ok bool) {
  1808  	var needInt, needFloat int
  1809  	for _, eb := range ebs {
  1810  		if eb.isFloat {
  1811  			needFloat++
  1812  			continue
  1813  		}
  1814  		needInt++
  1815  	}
  1816  	if *intIdx+needInt > len(intRegs) || *floatIdx+needFloat > len(floatRegs) {
  1817  		return nil, false, false
  1818  	}
  1819  	regs = make([]string, len(ebs))
  1820  	allFloat = true
  1821  	for k, eb := range ebs {
  1822  		if eb.isFloat {
  1823  			regs[k] = floatRegs[*floatIdx]
  1824  			*floatIdx++
  1825  			continue
  1826  		}
  1827  		regs[k] = intRegs[*intIdx]
  1828  		*intIdx++
  1829  		allFloat = false
  1830  	}
  1831  	return regs, allFloat, true
  1832  }
  1833  
  1834  // amd64AssignRet assigns System V AMD64 composite return values to AX/DX and
  1835  // X0/X1 according to their eightbyte classes, or to a hidden sret pointer in DI
  1836  // (SysV AMD64 psABI Section 3.2.3, "Returning of Values").
  1837  func amd64AssignRet(cfg *ABIConfig, fn BindingFunc, info typeInfo, st *abiState) RetLoc {
  1838  	if !info.composite {
  1839  		return defaultAssignRet(cfg, fn, info, st)
  1840  	}
  1841  	if ebs, ok := classifySysVStruct(info); ok {
  1842  		var retInt, retFloat int
  1843  		if regs, allFloat, fit := assignSysVRegs(ebs, cfg.IntRetRegs, cfg.FloatRetRegs, &retInt, &retFloat); fit {
  1844  			return RetLoc{Size: info.size, Regs: regs, IsFloat: allFloat}
  1845  		}
  1846  	}
  1847  	st.intIdx = 1
  1848  	return RetLoc{Size: info.size, Indirect: true}
  1849  }
  1850  
  1851  // amd64AssignParam assigns System V AMD64 parameters per SysV AMD64 psABI
  1852  // Section 3.2.3, placing aggregates all-or-nothing in registers when enough
  1853  // integer and SSE registers remain and spilling to 8-byte-aligned stack slots
  1854  // otherwise.
  1855  func amd64AssignParam(cfg *ABIConfig, _ BindingFunc, _ int, info typeInfo, st *abiState) ParamLoc {
  1856  	if info.composite {
  1857  		if ebs, ok := classifySysVStruct(info); ok {
  1858  			if regs, allFloat, fit := assignSysVRegs(ebs, cfg.IntRegs, cfg.FloatRegs, &st.intIdx, &st.floatIdx); fit {
  1859  				return ParamLoc{Size: info.size, Regs: regs, IsFloat: allFloat}
  1860  			}
  1861  		}
  1862  		return cfg.assignStackParam(info.size, false, st)
  1863  	}
  1864  	if info.isFloat {
  1865  		return cfg.assignFloatParam(info, st)
  1866  	}
  1867  	return cfg.assignIntParam(info, st)
  1868  }
  1869  
  1870  // amd64CompositeRegSlots maps each eightbyte of a register-passed or
  1871  // register-returned SysV AMD64 struct to its integer or SSE register piece.
  1872  func amd64CompositeRegSlots(_ *ABIConfig, info typeInfo, _ bool, regs []string) ([]regSlot, bool) {
  1873  	ebs, ok := classifySysVStruct(info)
  1874  	if !ok || len(ebs) != len(regs) {
  1875  		return nil, false
  1876  	}
  1877  	slots := make([]regSlot, len(regs))
  1878  	for k, r := range regs {
  1879  		slots[k] = regSlot{reg: r, offset: int64(k) * 8, size: ebs[k].size, isFloat: ebs[k].isFloat}
  1880  	}
  1881  	return slots, true
  1882  }
  1883  
  1884  var amd64ABI = &ABIConfig{
  1885  	Arch:              "amd64",
  1886  	PtrSize:           8,
  1887  	CLongSize:         8,
  1888  	StackAlign:        16,
  1889  	IntRegs:           []string{"DI", "SI", "DX", "CX", "R8", "R9"},
  1890  	FloatRegs:         []string{"X0", "X1", "X2", "X3", "X4", "X5", "X6", "X7"},
  1891  	IntRetRegs:        []string{"AX", "DX"},
  1892  	FloatRetRegs:      []string{"X0", "X1"},
  1893  	MaxRegStructSize:  16,
  1894  	IndirectRetReg:    "DI",
  1895  	IndirectRetInArg:  true,
  1896  	AssignParam:       amd64AssignParam,
  1897  	AssignRet:         amd64AssignRet,
  1898  	CompositeRegSlots: amd64CompositeRegSlots,
  1899  	SPReg:             "SP",
  1900  	CalleeSavedReg:    "R12",
  1901  	TmpReg:            "R11",
  1902  	TmpReg2:           "R10",
  1903  	ZeroVal:           "$0",
  1904  	asm: asmOps{
  1905  		mov:   "MOVQ",
  1906  		loadB: "MOVBLSX", loadBU: "MOVBLZX", loadH: "MOVWLSX", loadHU: "MOVWLZX", loadW: "MOVL", loadWU: "MOVL",
  1907  		storeB: "MOVB", storeH: "MOVW", storeW: "MOVL",
  1908  		fmovS: "MOVSS", fmovD: "MOVSD",
  1909  		shl: "SHLQ", shr: "SHRQ", or: "ORQ", add: "ADDQ", sub: "SUBQ", lea: "LEAQ",
  1910  		twoOpALU: true, twoOpShift: true, useAdjSP: true,
  1911  	},
  1912  	// System V AMD64 psABI Section 3.5.7 requires AL to hold an upper bound
  1913  	// (0..8) on the number of vector registers used to pass arguments to a
  1914  	// variadic (or unprototyped) C function. Always set AX—clearing it when
  1915  	// FloatRegCount == 0—since a bound C function (such as open, fcntl, or
  1916  	// ioctl) may be variadic in C.
  1917  	PreCall: func(cfg *ABIConfig, w io.Writer, _ BindingFunc, lay FuncLayout) {
  1918  		if lay.FloatRegCount == 0 {
  1919  			fmt.Fprintf(w, "\tXORL\tAX, AX\n")
  1920  		} else {
  1921  			fmt.Fprintf(w, "\tMOVL\t$%d, AX\n", min(lay.FloatRegCount, len(cfg.FloatRegs)))
  1922  		}
  1923  	},
  1924  	StackArgAddr: func(stackOff, _ int64) (string, int64) {
  1925  		return "BP", 16 + stackOff
  1926  	},
  1927  }
  1928  
  1929  // Windows x64 (Microsoft x64) C calling convention.
  1930  //
  1931  // Specification: "x64 calling convention", Microsoft Learn,
  1932  // https://learn.microsoft.com/en-us/cpp/build/x64-calling-convention.
  1933  //
  1934  // Summary:
  1935  //   - The first four argument positions use shared positional slots: CX/X0,
  1936  //     DX/X1, R8/X2, and R9/X3; later arguments pass in 8-byte stack slots above
  1937  //     a mandatory 32-byte caller-allocated shadow ("home") space
  1938  //     ("Parameter passing").
  1939  //   - Aggregates of exactly 1, 2, 4, or 8 bytes pass and return by value in a
  1940  //     single GPR (even if all fields are floating-point); all other aggregate
  1941  //     sizes pass by caller-allocated pointer and return via a hidden sret
  1942  //     pointer in CX that consumes positional slot 0 ("Return values").
  1943  //   - Scalar integer/pointer results return in AX; floating-point results
  1944  //     return in X0.
  1945  
  1946  // isWin64RegStructSize reports whether a composite byte size is passed and
  1947  // returned directly in a GPR under the Windows x64 (and x86) C ABI.
  1948  func isWin64RegStructSize(size int64) bool {
  1949  	return size == 1 || size == 2 || size == 4 || size == 8
  1950  }
  1951  
  1952  // win64AssignRet assigns Windows x64 composite returns of size 1, 2, 4, or 8
  1953  // bytes to AX, and all other composite sizes to a hidden sret pointer in CX
  1954  // consuming positional slot 0 ("Return values" in the x64 calling convention).
  1955  func win64AssignRet(cfg *ABIConfig, fn BindingFunc, info typeInfo, st *abiState) RetLoc {
  1956  	if !info.composite {
  1957  		return defaultAssignRet(cfg, fn, info, st)
  1958  	}
  1959  	if isWin64RegStructSize(info.size) {
  1960  		return RetLoc{Size: info.size, Regs: []string{cfg.IntRetRegs[0]}}
  1961  	}
  1962  	st.intIdx = 1
  1963  	st.floatIdx = 1
  1964  	return RetLoc{Size: info.size, Indirect: true}
  1965  }
  1966  
  1967  // win64AssignParam implements Windows x64 positional argument allocation
  1968  // across the 4 shared register slots (CX/X0, DX/X1, R8/X2, R9/X3), passing
  1969  // non-power-of-two or >8-byte structs by hidden pointer ("Parameter passing"
  1970  // in the x64 calling convention).
  1971  func win64AssignParam(cfg *ABIConfig, _ BindingFunc, _ int, info typeInfo, st *abiState) ParamLoc {
  1972  	if info.size == 0 {
  1973  		return ParamLoc{}
  1974  	}
  1975  	slot := max(st.intIdx, st.floatIdx)
  1976  	loc := ParamLoc{Size: info.size, IsFloat: info.isFloat}
  1977  	if info.composite && !isWin64RegStructSize(info.size) {
  1978  		loc.PassByPtr = true
  1979  	}
  1980  	if info.isFloat {
  1981  		if slot < len(cfg.FloatRegs) {
  1982  			loc.Regs = []string{cfg.FloatRegs[slot]}
  1983  			slot++
  1984  		} else {
  1985  			loc.StackOff = st.stackOff
  1986  			st.stackOff += 8
  1987  		}
  1988  	} else if slot < len(cfg.IntRegs) {
  1989  		loc.Regs = []string{cfg.IntRegs[slot]}
  1990  		slot++
  1991  	} else {
  1992  		loc.StackOff = st.stackOff
  1993  		st.stackOff += 8
  1994  	}
  1995  	st.intIdx, st.floatIdx = slot, slot
  1996  	return loc
  1997  }
  1998  
  1999  // newWin64ABI derives the Windows x64 ABIConfig from amd64ABI, configuring
  2000  // the 32-byte home space, positional register sets, and PE IAT indirect calls.
  2001  func newWin64ABI() *ABIConfig {
  2002  	cfg := *amd64ABI
  2003  	cfg.OS = "windows"
  2004  	cfg.CLongSize = 4
  2005  	cfg.ShadowSpace = 32
  2006  	cfg.LocalFrameOff = 32
  2007  	cfg.IndirectSymCall = true
  2008  	cfg.IntRegs = []string{"CX", "DX", "R8", "R9"}
  2009  	cfg.FloatRegs = []string{"X0", "X1", "X2", "X3"}
  2010  	cfg.IntRetRegs = []string{"AX"}
  2011  	cfg.FloatRetRegs = []string{"X0"}
  2012  	cfg.MaxRegStructSize = 8
  2013  	cfg.IndirectRetReg = "CX"
  2014  	cfg.PreCall = nil
  2015  	cfg.AssignParam = win64AssignParam
  2016  	cfg.AssignRet = win64AssignRet
  2017  	cfg.CompositeRegSlots = nil
  2018  	return &cfg
  2019  }
  2020  
  2021  var win64ABI = newWin64ABI()
  2022  
  2023  // ARM64 (AArch64) C calling convention (AAPCS64 and Darwin/Apple ARM64).
  2024  //
  2025  // Specifications:
  2026  //   - "Procedure Call Standard for the Arm 64-bit Architecture (AAPCS64)",
  2027  //     Section 6 ("The Base Procedure Call Standard"),
  2028  //     https://github.com/ARM-software/abi-aa/blob/main/aapcs64/aapcs64.rst
  2029  //   - Apple ARM64 ABI differences: "Writing ARM64 code for Apple platforms",
  2030  //     https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms
  2031  //
  2032  // Summary:
  2033  //   - Integer and pointer arguments use R0..R7; floating-point scalar arguments
  2034  //     use F0..F7 (AAPCS64 Section 6.8.2).
  2035  //   - Homogeneous Floating-Point Aggregates (HFAs) of 1 to 4 float32 or float64
  2036  //     elements with no padding pass in consecutive FP registers F0..F7 (or
  2037  //     spill to the stack while exhausting remaining FP registers) and return in
  2038  //     F0..F3 (Sections 5.9.5.1 and 6.8.2 Stage C.1–C.5).
  2039  //   - Non-HFA composites up to 16 bytes pass in consecutive GPRs R0..R7 (without
  2040  //     backfilling GPRs once a multi-register argument spills, Stage C.14) and
  2041  //     return in R0..R1.
  2042  //   - Non-HFA composites larger than 16 bytes pass by caller-allocated copy via
  2043  //     a pointer in a GPR or stack slot (Stage B.4), and return via a dedicated
  2044  //     indirect result address in R8 (XR) without consuming R0 (Section 6.9).
  2045  //   - The stack pointer (RSP) is 16-byte aligned at call boundaries.
  2046  //   - On Apple platforms (darwin/arm64, ios/arm64), non-variadic narrow scalar
  2047  //     and float32 HFA stack arguments pack at their natural alignment with
  2048  //     exact-width stores, whereas non-HFA composites <= 16 bytes and hidden
  2049  //     PassByPtr pointers remain 8-byte aligned.
  2050  
  2051  // classifyHFA reports whether composite type info is a Homogeneous
  2052  // Floating-Point Aggregate (1 to 4 identically sized float32 or float64
  2053  // members with no padding) per AAPCS32/AAPCS64, returning its element
  2054  // size and member count.
  2055  func classifyHFA(info typeInfo) (elemSize int64, count int, isHFA bool) {
  2056  	return classifyHFAMax(info, 4)
  2057  }
  2058  
  2059  // classifyHFAMax reports whether composite type info is an HFA of 1 to maxCount
  2060  // identically sized float32 or float64 members with no padding.
  2061  func classifyHFAMax(info typeInfo, maxCount int) (elemSize int64, count int, isHFA bool) {
  2062  	if info.size <= 0 || !info.fieldsOK || len(info.fields) < 1 || len(info.fields) > maxCount {
  2063  		return 0, 0, false
  2064  	}
  2065  	elemSize = info.fields[0].size
  2066  	if !info.fields[0].isFloat || (elemSize != 4 && elemSize != 8) || info.size != int64(len(info.fields))*elemSize {
  2067  		return 0, 0, false
  2068  	}
  2069  	for i, f := range info.fields {
  2070  		if !f.isFloat || f.size != elemSize || f.offset != int64(i)*elemSize {
  2071  			return 0, 0, false
  2072  		}
  2073  	}
  2074  	return elemSize, len(info.fields), true
  2075  }
  2076  
  2077  // arm64AssignRet returns Homogeneous Floating-Point Aggregates in F0..F3 and
  2078  // falls back to defaultAssignRet (R0..R1 or indirect sret in R8) otherwise
  2079  // (AAPCS64 Section 6.9).
  2080  func arm64AssignRet(cfg *ABIConfig, fn BindingFunc, info typeInfo, st *abiState) RetLoc {
  2081  	if info.composite {
  2082  		if _, count, ok := classifyHFA(info); ok {
  2083  			return RetLoc{Size: info.size, Regs: slices.Clone(cfg.FloatRetRegs[:count]), IsFloat: true}
  2084  		}
  2085  	}
  2086  	return defaultAssignRet(cfg, fn, info, st)
  2087  }
  2088  
  2089  // arm64AssignParam allocates AAPCS64 parameters per Section 6.8.2: HFAs in
  2090  // F0..F7, floats in F0..F7, >16-byte composites by pointer, and integers or
  2091  // <=16-byte non-HFA composites in R0..R7 without GPR backfilling.
  2092  func arm64AssignParam(cfg *ABIConfig, _ BindingFunc, _ int, info typeInfo, st *abiState) ParamLoc {
  2093  	if info.composite {
  2094  		if _, count, ok := classifyHFA(info); ok {
  2095  			if st.floatIdx+count <= len(cfg.FloatRegs) {
  2096  				regs := slices.Clone(cfg.FloatRegs[st.floatIdx : st.floatIdx+count])
  2097  				st.floatIdx += count
  2098  				return ParamLoc{Size: info.size, IsFloat: true, Regs: regs}
  2099  			}
  2100  			st.floatIdx = len(cfg.FloatRegs)
  2101  			if cfg.PackStackArgs {
  2102  				return cfg.assignPackedStackParam(info.size, info.align, true, st)
  2103  			}
  2104  			return cfg.assignStackParam(info.size, true, st)
  2105  		}
  2106  		if info.size > cfg.MaxRegStructSize {
  2107  			return cfg.assignPtrParam(info.size, st)
  2108  		}
  2109  	}
  2110  	if info.isFloat {
  2111  		return cfg.assignFloatParam(info, st)
  2112  	}
  2113  	loc := cfg.assignIntParam(info, st)
  2114  	if info.size > 0 && len(loc.Regs) == 0 {
  2115  		st.intIdx = len(cfg.IntRegs)
  2116  	}
  2117  	return loc
  2118  }
  2119  
  2120  // hfaCompositeRegSlots maps each member of a register-passed or
  2121  // register-returned HFA to its consecutive floating-point register.
  2122  func hfaCompositeRegSlots(_ *ABIConfig, info typeInfo, isFloat bool, regs []string) ([]regSlot, bool) {
  2123  	if !isFloat {
  2124  		return nil, false
  2125  	}
  2126  	elemSz := info.size / int64(len(regs))
  2127  	if info.fieldsOK && len(info.fields) > 0 {
  2128  		elemSz = info.fields[0].size
  2129  	}
  2130  	slots := make([]regSlot, len(regs))
  2131  	for k, r := range regs {
  2132  		slots[k] = regSlot{reg: r, offset: int64(k) * elemSz, size: elemSz, isFloat: true}
  2133  	}
  2134  	return slots, true
  2135  }
  2136  
  2137  // emitARM64TrampolinePrologue emits a NOFRAME arm64 Go-to-C trampoline prologue
  2138  // and returns its matching epilogue. Maintaining a single frame with an AAPCS64
  2139  // (R29, R30) frame record at the top (so CFA = R29+16 = caller SP) avoids
  2140  // placing R29 below RSP where C callees clobber it, and keeps 0(RSP) = saved R30
  2141  // via atomic STP.W/LDP.P whenever no C stack arguments occupy 0(RSP).
  2142  func emitARM64TrampolinePrologue(w io.Writer, lay FuncLayout) func(io.Writer) {
  2143  	if !lay.hasStackArgs() {
  2144  		total := max(int64(16), lay.StackSize) + 16
  2145  		fpOff := total - 16
  2146  		if total <= 504 {
  2147  			fmt.Fprintf(w, "\tSTP.W\t(R30, R19), -%d(RSP)\n", total)
  2148  			fmt.Fprintf(w, "\tSTP\t(R29, R30), %d(RSP)\n", fpOff)
  2149  		} else {
  2150  			fmt.Fprintf(w, "\tSUB\t$%d, RSP\n", total)
  2151  			fmt.Fprintf(w, "\tMOVD\tR30, 0(RSP)\n")
  2152  			fmt.Fprintf(w, "\tMOVD\tR19, 8(RSP)\n")
  2153  			fmt.Fprintf(w, "\tMOVD\tR29, %d(RSP)\n", fpOff)
  2154  			fmt.Fprintf(w, "\tMOVD\tR30, %d(RSP)\n", fpOff+8)
  2155  		}
  2156  		fmt.Fprintf(w, "\tADD\t$%d, RSP, R29\n", fpOff)
  2157  		fmt.Fprintf(w, "\tMOVD\tR0, R19\n")
  2158  		return func(w io.Writer) {
  2159  			fmt.Fprintf(w, "\tMOVD\t%d(RSP), R29\n", fpOff)
  2160  			if total <= 504 {
  2161  				fmt.Fprintf(w, "\tLDP.P\t%d(RSP), (R30, R19)\n", total)
  2162  			} else {
  2163  				fmt.Fprintf(w, "\tMOVD\t8(RSP), R19\n")
  2164  				fmt.Fprintf(w, "\tMOVD\t0(RSP), R30\n")
  2165  				fmt.Fprintf(w, "\tADD\t$%d, RSP\n", total)
  2166  			}
  2167  		}
  2168  	}
  2169  	total := lay.StackSize + 32
  2170  	fpOff := total - 16
  2171  	r19Off := total - 32
  2172  	fmt.Fprintf(w, "\tSUB\t$%d, RSP\n", total)
  2173  	if fpOff <= 504 {
  2174  		fmt.Fprintf(w, "\tSTP\t(R29, R30), %d(RSP)\n", fpOff)
  2175  	} else {
  2176  		fmt.Fprintf(w, "\tMOVD\tR29, %d(RSP)\n", fpOff)
  2177  		fmt.Fprintf(w, "\tMOVD\tR30, %d(RSP)\n", fpOff+8)
  2178  	}
  2179  	fmt.Fprintf(w, "\tADD\t$%d, RSP, R29\n", fpOff)
  2180  	fmt.Fprintf(w, "\tMOVD\tR19, %d(RSP)\n", r19Off)
  2181  	fmt.Fprintf(w, "\tMOVD\tR0, R19\n")
  2182  	return func(w io.Writer) {
  2183  		fmt.Fprintf(w, "\tMOVD\t%d(RSP), R19\n", r19Off)
  2184  		if fpOff <= 504 {
  2185  			fmt.Fprintf(w, "\tLDP\t%d(RSP), (R29, R30)\n", fpOff)
  2186  		} else {
  2187  			fmt.Fprintf(w, "\tMOVD\t%d(RSP), R29\n", fpOff)
  2188  			fmt.Fprintf(w, "\tMOVD\t%d(RSP), R30\n", fpOff+8)
  2189  		}
  2190  		fmt.Fprintf(w, "\tADD\t$%d, RSP\n", total)
  2191  	}
  2192  }
  2193  
  2194  var arm64ABI = &ABIConfig{
  2195  	Arch:              "arm64",
  2196  	PtrSize:           8,
  2197  	CLongSize:         8,
  2198  	StackAlign:        16,
  2199  	IntRegs:           []string{"R0", "R1", "R2", "R3", "R4", "R5", "R6", "R7"},
  2200  	FloatRegs:         []string{"F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7"},
  2201  	IntRetRegs:        []string{"R0", "R1"},
  2202  	FloatRetRegs:      []string{"F0", "F1", "F2", "F3"},
  2203  	MaxRegStructSize:  16,
  2204  	IndirectRetReg:    "R8",
  2205  	AssignParam:       arm64AssignParam,
  2206  	AssignRet:         arm64AssignRet,
  2207  	CompositeRegSlots: hfaCompositeRegSlots,
  2208  	SPReg:             "RSP",
  2209  	CalleeSavedReg:    "R19",
  2210  	TmpReg:            "R12",
  2211  	TmpReg2:           "R13",
  2212  	LRReserve:         16,
  2213  	ZeroVal:           "ZR",
  2214  	LocalFrameOff:     16,
  2215  	asm: asmOps{
  2216  		mov:   "MOVD",
  2217  		loadB: "MOVB", loadBU: "MOVBU", loadH: "MOVH", loadHU: "MOVHU", loadW: "MOVW", loadWU: "MOVWU",
  2218  		storeB: "MOVB", storeH: "MOVH", storeW: "MOVW",
  2219  		fmovS: "FMOVS", fmovD: "FMOVD",
  2220  		shl: "LSL", shr: "LSR", or: "ORR", add: "ADD", sub: "SUB",
  2221  	},
  2222  	TrampolinePrologue: emitARM64TrampolinePrologue,
  2223  	CallbackPrologue: func(w io.Writer, frameSize int64) int64 {
  2224  		total, small := arm64CallbackFrame(frameSize)
  2225  		fpOff := total - 16
  2226  		if small {
  2227  			fmt.Fprintf(w, "\tSTP.W\t(R30, R27), -%d(RSP)\n", total)
  2228  			fmt.Fprintf(w, "\tSTP\t(R29, R30), %d(RSP)\n", fpOff)
  2229  		} else {
  2230  			// total may not be encodable as an ADD/SUB immediate, in which
  2231  			// case the assembler materializes it in REGTMP (R27), which is
  2232  			// callee-saved in the C ABI. Save the frame record and R27 with
  2233  			// small pre-indexed stores before the large SP adjustment.
  2234  			fmt.Fprintf(w, "\tSTP.W\t(R29, R30), -16(RSP)\n")
  2235  			fmt.Fprintf(w, "\tMOVD.W\tR27, -16(RSP)\n")
  2236  			fmt.Fprintf(w, "\tSUB\t$%d, RSP\n", total-32)
  2237  			fmt.Fprintf(w, "\tMOVD\tR30, 0(RSP)\n")
  2238  		}
  2239  		fmt.Fprintf(w, "\tADD\t$%d, RSP, R29\n", fpOff)
  2240  		return total
  2241  	},
  2242  	CallbackEpilogue: func(w io.Writer, frameSize int64, _ bool) {
  2243  		total, small := arm64CallbackFrame(frameSize)
  2244  		if small {
  2245  			fmt.Fprintf(w, "\tMOVD\t%d(RSP), R29\n", total-16)
  2246  			fmt.Fprintf(w, "\tLDP.P\t%d(RSP), (R30, R27)\n", total)
  2247  		} else {
  2248  			// Undo the large SP adjustment (possibly via REGTMP) before
  2249  			// restoring R27 and the frame record.
  2250  			fmt.Fprintf(w, "\tADD\t$%d, RSP\n", total-32)
  2251  			fmt.Fprintf(w, "\tMOVD.P\t16(RSP), R27\n")
  2252  			fmt.Fprintf(w, "\tLDP.P\t16(RSP), (R29, R30)\n")
  2253  		}
  2254  		fmt.Fprintf(w, "\tRET\n")
  2255  	},
  2256  }
  2257  
  2258  // arm64CallbackFrame returns the total C stack frame size of an arm64
  2259  // callback trampoline whose local Go argument area is frameSize bytes, and
  2260  // whether it uses the compact frame layout:
  2261  //
  2262  //	0(RSP)          saved LR (Go frame convention)
  2263  //	8(RSP)          saved R27 (compact layout only)
  2264  //	16(RSP)         local Go argument area (frameSize bytes)
  2265  //	total-32(RSP)   saved R27 (large layout only)
  2266  //	total-16(RSP)   frame record (R29, R30)
  2267  //
  2268  // The compact layout is used when total fits the signed, scaled 7-bit
  2269  // immediate of STP.W/LDP.P.
  2270  func arm64CallbackFrame(frameSize int64) (total int64, small bool) {
  2271  	total = 32 + frameSize
  2272  	if total <= 504 {
  2273  		return total, true
  2274  	}
  2275  	return 48 + frameSize, false
  2276  }
  2277  
  2278  // 32-bit x86 (i386) C calling convention:
  2279  //   - SysV i386 psABI Section 2.2: https://gitlab.com/x86-psABIs/i386-ABI
  2280  //   - Windows x86 (__cdecl): https://learn.microsoft.com/en-us/cpp/cpp/argument-passing-and-naming-conventions
  2281  
  2282  func win32AssignRet(cfg *ABIConfig, fn BindingFunc, info typeInfo, st *abiState) RetLoc {
  2283  	if info.composite && isWin64RegStructSize(info.size) {
  2284  		if info.size <= 4 {
  2285  			return RetLoc{Size: info.size, Regs: []string{"AX"}}
  2286  		}
  2287  		return RetLoc{Size: info.size, Regs: []string{"AX", "DX"}}
  2288  	}
  2289  	return defaultAssignRet(cfg, fn, info, st)
  2290  }
  2291  
  2292  // sysv386AssignRet implements return values on Linux and NetBSD, whose C
  2293  // compilers return every composite through a hidden pointer that the callee
  2294  // pops, except _Complex float (complex64), which is not an aggregate in the
  2295  // SysV i386 psABI and is returned in AX:DX like a 64-bit integer.
  2296  // _Complex double (complex128) is returned through a hidden pointer.
  2297  func sysv386AssignRet(cfg *ABIConfig, fn BindingFunc, info typeInfo, st *abiState) RetLoc {
  2298  	if info.isComplex && info.size == 8 {
  2299  		return RetLoc{Size: info.size, Regs: []string{"AX", "DX"}}
  2300  	}
  2301  	return defaultAssignRet(cfg, fn, info, st)
  2302  }
  2303  
  2304  // bsd386AssignRet implements struct return on FreeBSD and OpenBSD, whose C
  2305  // compilers default to -freg-struct-return on 386: as on Windows, composites
  2306  // of 1, 2, 4, or 8 bytes are returned in AX or AX:DX, except that a composite
  2307  // whose only element is a float or double is returned in F0. Other composites
  2308  // are returned through a hidden pointer, which the callee pops.
  2309  func bsd386AssignRet(cfg *ABIConfig, fn BindingFunc, info typeInfo, st *abiState) RetLoc {
  2310  	if info.composite && isWin64RegStructSize(info.size) && info.fieldsOK &&
  2311  		len(info.fields) == 1 && info.fields[0].isFloat && info.fields[0].size == info.size {
  2312  		return RetLoc{Size: info.size, Regs: []string{"F0"}, IsFloat: true}
  2313  	}
  2314  	return win32AssignRet(cfg, fn, info, st)
  2315  }
  2316  
  2317  func i386AssignParam(cfg *ABIConfig, _ BindingFunc, _ int, info typeInfo, st *abiState) ParamLoc {
  2318  	if info.size == 0 {
  2319  		return ParamLoc{IsFloat: info.isFloat}
  2320  	}
  2321  	return cfg.assignStackParam(info.size, info.isFloat, st)
  2322  }
  2323  
  2324  var i386ABI = &ABIConfig{
  2325  	Arch:               "386",
  2326  	PtrSize:            4,
  2327  	CLongSize:          4,
  2328  	StackAlign:         16,
  2329  	IndirectRetOnStack: true,
  2330  	SysVI386SretPop:    true,
  2331  	IntRetRegs:         []string{"AX", "DX"},
  2332  	FloatRetRegs:       []string{"F0"},
  2333  	AssignParam:        i386AssignParam,
  2334  	AssignRet:          sysv386AssignRet,
  2335  	SPReg:              "SP",
  2336  	CalleeSavedReg:     "BX",
  2337  	TmpReg:             "CX",
  2338  	TmpReg2:            "DX",
  2339  	ZeroVal:            "$0",
  2340  	asm: asmOps{
  2341  		mov:   "MOVL",
  2342  		loadB: "MOVBLSX", loadBU: "MOVBLZX", loadH: "MOVWLSX", loadHU: "MOVWLZX", loadW: "MOVL", loadWU: "MOVL",
  2343  		storeB: "MOVB", storeH: "MOVW", storeW: "MOVL",
  2344  		shl: "SHLL", shr: "SHRL", or: "ORL", add: "ADDL", sub: "SUBL", lea: "LEAL",
  2345  		twoOpALU: true, twoOpShift: true, useAdjSP: true,
  2346  	},
  2347  	StackArgAddr: func(stackOff, _ int64) (string, int64) {
  2348  		return "BP", 8 + stackOff
  2349  	},
  2350  	LoadFloat: func(w io.Writer, base string, off, size int64, reg string) bool {
  2351  		if reg != "F0" {
  2352  			return false
  2353  		}
  2354  		if size == 4 {
  2355  			fmt.Fprintf(w, "\tFMOVF\t%d(%s), F0\n", off, base)
  2356  		} else {
  2357  			fmt.Fprintf(w, "\tFMOVD\t%d(%s), F0\n", off, base)
  2358  		}
  2359  		return true
  2360  	},
  2361  	StoreFloat: func(w io.Writer, reg, base string, off, size int64) bool {
  2362  		if reg != "F0" {
  2363  			return false
  2364  		}
  2365  		if size == 4 {
  2366  			fmt.Fprintf(w, "\tFMOVFP\tF0, %d(%s)\n", off, base)
  2367  		} else {
  2368  			fmt.Fprintf(w, "\tFMOVDP\tF0, %d(%s)\n", off, base)
  2369  		}
  2370  		return true
  2371  	},
  2372  	Prologue: func(w io.Writer) func(w io.Writer) {
  2373  		fmt.Fprintf(w, "\tPUSHL\tBP\n")
  2374  		fmt.Fprintf(w, "\tMOVL\tSP, BP\n")
  2375  		fmt.Fprintf(w, "\tADJSP\t$8\n")
  2376  		fmt.Fprintf(w, "\tMOVL\tBX, -4(BP)\n")
  2377  		fmt.Fprintf(w, "\tMOVL\t8(BP), BX\n")
  2378  		return func(w io.Writer) {
  2379  			fmt.Fprintf(w, "\tMOVL\t-4(BP), BX\n")
  2380  			fmt.Fprintf(w, "\tADJSP\t$-8\n")
  2381  			fmt.Fprintf(w, "\tPOPL\tBP\n")
  2382  		}
  2383  	},
  2384  	CallbackPrologue: func(w io.Writer, frameSize int64) int64 {
  2385  		fmt.Fprintf(w, "\tPUSHL\tBP\n")
  2386  		fmt.Fprintf(w, "\tMOVL\tSP, BP\n")
  2387  		fmt.Fprintf(w, "\tADJSP\t$%d\n", frameSize+8)
  2388  		// Save C callee-saved BX in the 8-byte alignment padding: under -dynlink,
  2389  		// obj6 prepends LEAL _GLOBAL_OFFSET_TABLE_, BX before non-local CALLs.
  2390  		fmt.Fprintf(w, "\tMOVL\tBX, -4(BP)\n")
  2391  		return 0
  2392  	},
  2393  	CallbackEpilogue: func(w io.Writer, frameSize int64, sretPop bool) {
  2394  		fmt.Fprintf(w, "\tMOVL\t-4(BP), BX\n")
  2395  		fmt.Fprintf(w, "\tADJSP\t$-%d\n", frameSize+8)
  2396  		fmt.Fprintf(w, "\tPOPL\tBP\n")
  2397  		if sretPop {
  2398  			fmt.Fprintf(w, "\tBYTE\t$0xc2\n\tWORD\t$4\n")
  2399  		} else {
  2400  			fmt.Fprintf(w, "\tRET\n")
  2401  		}
  2402  	},
  2403  	CallCrosscall2: func(w io.Writer, fnName string, frameSize, ctxtOff int64) {
  2404  		fmt.Fprintf(w, "\tCALL\t_cgo_wait_runtime_init_done(SB)\n")
  2405  		fmt.Fprintf(w, "\tMOVL\tAX, %d(SP)\n", ctxtOff)
  2406  		fmt.Fprintf(w, "\tADJSP\t$16\n")
  2407  		fmt.Fprintf(w, "\tMOVL\tAX, 12(SP)\n")
  2408  		fmt.Fprintf(w, "\tMOVL\t·_cgo_fn_%s(SB), AX\n", fnName)
  2409  		fmt.Fprintf(w, "\tMOVL\t0(AX), AX\n")
  2410  		fmt.Fprintf(w, "\tMOVL\tAX, 0(SP)\n")
  2411  		fmt.Fprintf(w, "\tLEAL\t16(SP), AX\n")
  2412  		fmt.Fprintf(w, "\tMOVL\tAX, 4(SP)\n")
  2413  		fmt.Fprintf(w, "\tMOVL\t$%d, 8(SP)\n", frameSize)
  2414  		fmt.Fprintf(w, "\tCALL\tcrosscall2(SB)\n")
  2415  		fmt.Fprintf(w, "\tMOVL\t%d(SP), AX\n", 16+ctxtOff)
  2416  		fmt.Fprintf(w, "\tMOVL\tAX, 0(SP)\n")
  2417  		fmt.Fprintf(w, "\tCALL\t_cgo_release_context(SB)\n")
  2418  		fmt.Fprintf(w, "\tADJSP\t$-16\n")
  2419  	},
  2420  }
  2421  
  2422  // 32-bit ARM C calling convention:
  2423  //   - AAPCS32 Sections 6 & 7.1 (VFP): https://github.com/ARM-software/abi-aa/blob/main/aapcs32/aapcs32.rst
  2424  //   - Android armeabi-v7a (soft-float): https://developer.android.com/ndk/guides/abis
  2425  //
  2426  // android/arm and openbsd/arm always use the base (soft-float) procedure
  2427  // call standard, which passes floating-point values in core registers.
  2428  // Other targets use the VFP variant unless GOARM selects soft float, since
  2429  // code built for a CPU without VFP cannot use VFP registers.
  2430  
  2431  // goarmSoftFloat reports whether GOARM selects soft float (GOARM=5, or a
  2432  // ",softfloat" suffix). It reads the environment at each call, rather than
  2433  // using buildcfg.GOARM computed at startup, so tests can change GOARM.
  2434  func goarmSoftFloat() bool {
  2435  	v := os.Getenv("GOARM")
  2436  	if v == "" {
  2437  		return buildcfg.GOARM.SoftFloat
  2438  	}
  2439  	if strings.HasSuffix(v, ",softfloat") {
  2440  		return true
  2441  	}
  2442  	if strings.HasSuffix(v, ",hardfloat") {
  2443  		return false
  2444  	}
  2445  	return v == "5"
  2446  }
  2447  
  2448  func arm32AssignRet(cfg *ABIConfig, fn BindingFunc, info typeInfo, st *abiState) RetLoc {
  2449  	if info.composite {
  2450  		if elemSz, count, ok := classifyHFA(info); ok {
  2451  			if elemSz == 8 {
  2452  				return RetLoc{Size: info.size, Regs: slices.Clone(cfg.FloatRetRegs[:count]), IsFloat: true}
  2453  			}
  2454  			regs := make([]string, count)
  2455  			for k := range count {
  2456  				regs[k] = fmt.Sprintf("S%d", k)
  2457  			}
  2458  			return RetLoc{Size: info.size, Regs: regs, IsFloat: true}
  2459  		}
  2460  	}
  2461  	if info.isFloat && info.size == 4 {
  2462  		return RetLoc{Size: 4, Regs: []string{"S0"}, IsFloat: true}
  2463  	}
  2464  	return defaultAssignRet(cfg, fn, info, st)
  2465  }
  2466  
  2467  func arm32AssignParam(cfg *ABIConfig, _ BindingFunc, _ int, info typeInfo, st *abiState) ParamLoc {
  2468  	if info.size == 0 {
  2469  		return ParamLoc{}
  2470  	}
  2471  	if len(cfg.FloatRegs) > 0 {
  2472  		elemSz, count, isVFP := info.size, 1, info.isFloat && (info.size == 4 || info.size == 8)
  2473  		if !isVFP && info.composite {
  2474  			elemSz, count, isVFP = classifyHFA(info)
  2475  		}
  2476  		if isVFP {
  2477  			step := int(elemSz / 4)
  2478  			lanes := count * step
  2479  			mask := (uint16(1) << lanes) - 1
  2480  			for s := 0; s <= 16-lanes; s += step {
  2481  				if st.vfpMask&(mask<<s) == 0 {
  2482  					st.vfpMask |= mask << s
  2483  					st.floatIdx += count
  2484  					regs := make([]string, count)
  2485  					for k := range count {
  2486  						if elemSz == 4 {
  2487  							regs[k] = fmt.Sprintf("S%d", s+k)
  2488  						} else {
  2489  							regs[k] = fmt.Sprintf("F%d", s/2+k)
  2490  						}
  2491  					}
  2492  					return ParamLoc{Size: info.size, IsFloat: true, Regs: regs}
  2493  				}
  2494  			}
  2495  			st.vfpMask = 0xffff
  2496  			if elemSz == 8 {
  2497  				st.stackOff = alignUp(st.stackOff, 8)
  2498  			}
  2499  			return cfg.assignStackParam(info.size, true, st)
  2500  		}
  2501  	}
  2502  
  2503  	need8 := (!info.composite && info.size == 8) || info.align == 8
  2504  	if need8 && st.intIdx < len(cfg.IntRegs) && st.intIdx%2 != 0 {
  2505  		st.intIdx++
  2506  	}
  2507  	numRegs := int((info.size + cfg.PtrSize - 1) / cfg.PtrSize)
  2508  	if st.intIdx < len(cfg.IntRegs) && st.intIdx+numRegs > len(cfg.IntRegs) && info.composite && st.stackOff == 0 {
  2509  		// AAPCS32 Section 6.1.1 Rule C.5: split a composite across the remaining
  2510  		// core registers R[intIdx]..R3 and the stack starting at 0(SP), but only
  2511  		// if no argument has been placed on the stack yet (NSAA == SP). Otherwise
  2512  		// Rules C.6-C.8 below place the composite wholly on the stack.
  2513  		regs := slices.Clone(cfg.IntRegs[st.intIdx:])
  2514  		regBytes := int64(len(regs)) * cfg.PtrSize
  2515  		stackBytes := info.size - regBytes
  2516  		st.intIdx = len(cfg.IntRegs)
  2517  		off := st.stackOff
  2518  		st.stackOff += alignUp(stackBytes, cfg.PtrSize)
  2519  		return ParamLoc{Size: info.size, Regs: regs, StackOff: off, StackBytes: stackBytes}
  2520  	}
  2521  	if st.intIdx+numRegs > len(cfg.IntRegs) {
  2522  		st.intIdx = len(cfg.IntRegs)
  2523  		if need8 {
  2524  			st.stackOff = alignUp(st.stackOff, 8)
  2525  		}
  2526  		return cfg.assignStackParam(info.size, false, st)
  2527  	}
  2528  	return cfg.assignIntParam(info, st)
  2529  }
  2530  
  2531  // emitARM32TrampolinePrologue emits a NOFRAME 32-bit arm Go-to-C trampoline
  2532  // prologue and returns its matching epilogue, keeping R13 8-byte aligned and
  2533  // atomically storing R14 at 0(R13) via MOVW.W/MOVW.P whenever no C stack
  2534  // arguments occupy 0(R13).
  2535  func emitARM32TrampolinePrologue(w io.Writer, lay FuncLayout) func(io.Writer) {
  2536  	if !lay.hasStackArgs() {
  2537  		total := max(int64(8), lay.StackSize)
  2538  		if total <= 4095 {
  2539  			fmt.Fprintf(w, "\tMOVW.W\tR14, -%d(R13)\n", total)
  2540  		} else {
  2541  			fmt.Fprintf(w, "\tSUB\t$%d, R13\n", total)
  2542  			fmt.Fprintf(w, "\tMOVW\tR14, 0(R13)\n")
  2543  		}
  2544  		fmt.Fprintf(w, "\tMOVW\tR0, R4\n")
  2545  		return func(w io.Writer) {
  2546  			if total <= 4095 {
  2547  				fmt.Fprintf(w, "\tMOVW.P\t%d(R13), R14\n", total)
  2548  			} else {
  2549  				fmt.Fprintf(w, "\tMOVW\t0(R13), R14\n")
  2550  				fmt.Fprintf(w, "\tADD\t$%d, R13\n", total)
  2551  			}
  2552  		}
  2553  	}
  2554  	// AAPCS32 places 5th+ arguments at 0(R13), so save R14 above them.
  2555  	total := lay.StackSize + 8
  2556  	lrOff := total - 4
  2557  	fmt.Fprintf(w, "\tSUB\t$%d, R13\n", total)
  2558  	fmt.Fprintf(w, "\tMOVW\tR14, %d(R13)\n", lrOff)
  2559  	fmt.Fprintf(w, "\tMOVW\tR0, R4\n")
  2560  	return func(w io.Writer) {
  2561  		fmt.Fprintf(w, "\tMOVW\t%d(R13), R14\n", lrOff)
  2562  		fmt.Fprintf(w, "\tADD\t$%d, R13\n", total)
  2563  	}
  2564  }
  2565  
  2566  var armABI = &ABIConfig{
  2567  	Arch:              "arm",
  2568  	PtrSize:           4,
  2569  	CLongSize:         4,
  2570  	StackAlign:        8,
  2571  	IntRegs:           []string{"R0", "R1", "R2", "R3"},
  2572  	FloatRegs:         []string{"F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7"},
  2573  	IntRetRegs:        []string{"R0", "R1"},
  2574  	FloatRetRegs:      []string{"F0", "F1", "F2", "F3"},
  2575  	MaxRegStructSize:  4,
  2576  	IndirectRetReg:    "R0",
  2577  	IndirectRetInArg:  true,
  2578  	AssignParam:       arm32AssignParam,
  2579  	AssignRet:         arm32AssignRet,
  2580  	CompositeRegSlots: hfaCompositeRegSlots,
  2581  	SPReg:             "R13",
  2582  	CalleeSavedReg:    "R4",
  2583  	TmpReg:            "R12",
  2584  	TmpReg2:           "R8",
  2585  	LRReserve:         8,
  2586  	LocalFrameOff:     8,
  2587  	StrictAlign:       true,
  2588  	asm: asmOps{
  2589  		mov:   "MOVW",
  2590  		loadB: "MOVB", loadBU: "MOVBU", loadH: "MOVH", loadHU: "MOVHU", loadW: "MOVW", loadWU: "MOVW",
  2591  		storeB: "MOVB", storeH: "MOVH", storeW: "MOVW",
  2592  		fmovS: "MOVF", fmovD: "MOVD",
  2593  		shl: "SLL", shr: "SRL", or: "ORR", add: "ADD", sub: "SUB",
  2594  		twoOpShift: true,
  2595  	},
  2596  	TrampolinePrologue: emitARM32TrampolinePrologue,
  2597  	CallbackPrologue: func(w io.Writer, frameSize int64) int64 {
  2598  		// Save callee-saved R8 (used as TmpReg2) alongside R11 (REGTMP) and R14 (LR).
  2599  		total := 16 + frameSize
  2600  		if total <= 4095 {
  2601  			fmt.Fprintf(w, "\tMOVW.W\tR14, -%d(R13)\n", total)
  2602  			fmt.Fprintf(w, "\tMOVW\tR8, 4(R13)\n")
  2603  			fmt.Fprintf(w, "\tMOVW\tR11, %d(R13)\n", 8+frameSize)
  2604  			return total
  2605  		}
  2606  		fmt.Fprintf(w, "\tSUB\t$8, R13\n")
  2607  		fmt.Fprintf(w, "\tMOVW\tR11, 0(R13)\n")
  2608  		fmt.Fprintf(w, "\tMOVW\tR8, 4(R13)\n")
  2609  		fmt.Fprintf(w, "\tSUB\t$%d, R13\n", 8+frameSize)
  2610  		fmt.Fprintf(w, "\tMOVW\tR14, 0(R13)\n")
  2611  		return total
  2612  	},
  2613  	CallbackEpilogue: func(w io.Writer, frameSize int64, _ bool) {
  2614  		total := 16 + frameSize
  2615  		if total <= 4095 {
  2616  			fmt.Fprintf(w, "\tMOVW\t%d(R13), R11\n", 8+frameSize)
  2617  			fmt.Fprintf(w, "\tMOVW\t4(R13), R8\n")
  2618  			fmt.Fprintf(w, "\tMOVW.P\t%d(R13), R14\n", total)
  2619  			fmt.Fprintf(w, "\tRET\n")
  2620  			return
  2621  		}
  2622  		fmt.Fprintf(w, "\tMOVW\t0(R13), R14\n")
  2623  		fmt.Fprintf(w, "\tADD\t$%d, R13\n", 8+frameSize)
  2624  		fmt.Fprintf(w, "\tMOVW\t4(R13), R8\n")
  2625  		fmt.Fprintf(w, "\tMOVW\t0(R13), R11\n")
  2626  		fmt.Fprintf(w, "\tADD\t$8, R13\n")
  2627  		fmt.Fprintf(w, "\tRET\n")
  2628  	},
  2629  	IsFloatReg: func(reg string) bool {
  2630  		return len(reg) >= 2 && reg[0] == 'S'
  2631  	},
  2632  	LoadFloat: func(w io.Writer, base string, off, _ int64, reg string) bool {
  2633  		if len(reg) < 2 || reg[0] != 'S' {
  2634  			return false
  2635  		}
  2636  		sIdx, _ := strconv.Atoi(reg[1:])
  2637  		if sIdx%2 == 0 {
  2638  			fmt.Fprintf(w, "\tMOVF\t%d(%s), F%d\n", off, base, sIdx/2)
  2639  		} else {
  2640  			// VMOV s(2n+1), R12 (transfer R12 to odd VFP single register).
  2641  			fmt.Fprintf(w, "\tMOVW\t%d(%s), R12\n", off, base)
  2642  			fmt.Fprintf(w, "\tWORD\t$0x%08x\n", 0xee00ca90|(uint32(sIdx/2)<<16))
  2643  		}
  2644  		return true
  2645  	},
  2646  	StoreFloat: func(w io.Writer, reg, base string, off, _ int64) bool {
  2647  		if len(reg) < 2 || reg[0] != 'S' {
  2648  			return false
  2649  		}
  2650  		sIdx, _ := strconv.Atoi(reg[1:])
  2651  		if sIdx%2 == 0 {
  2652  			fmt.Fprintf(w, "\tMOVF\tF%d, %d(%s)\n", sIdx/2, off, base)
  2653  		} else {
  2654  			// VMOV R12, s(2n+1) (transfer odd VFP single register to R12).
  2655  			fmt.Fprintf(w, "\tWORD\t$0x%08x\n", 0xee10ca90|(uint32(sIdx/2)<<16))
  2656  			fmt.Fprintf(w, "\tMOVW\tR12, %d(%s)\n", off, base)
  2657  		}
  2658  		return true
  2659  	},
  2660  }
  2661  
  2662  // 32-bit MIPS O32 C calling convention:
  2663  // "System V ABI: MIPS RISC Processor Supplement", 3rd Edition, Chapter 3.
  2664  
  2665  func mips32AssignParam(cfg *ABIConfig, _ BindingFunc, _ int, info typeInfo, st *abiState) ParamLoc {
  2666  	if info.size == 0 {
  2667  		return ParamLoc{}
  2668  	}
  2669  	nWords := int((info.size + 3) / 4)
  2670  	need8 := (!info.composite && info.size == 8) || info.align == 8
  2671  	if need8 && st.intIdx < 4 && st.intIdx%2 != 0 {
  2672  		st.intIdx++
  2673  	}
  2674  	loc := ParamLoc{Size: info.size, IsFloat: info.isFloat}
  2675  	// MIPS O32 only passes the first two floating-point arguments in F12/F14,
  2676  	// and only while no preceding non-float (or hidden sret) argument has been
  2677  	// seen. Once F14 is assigned or any non-float argument is encountered, all
  2678  	// subsequent arguments (including floats) are passed in GPRs or on the stack.
  2679  	if len(cfg.FloatRegs) > 0 && !st.fprsDisabled && info.isFloat && st.intIdx < 4 {
  2680  		switch {
  2681  		case info.size == 4 && st.intIdx == 0:
  2682  			loc.Regs = []string{"F12"}
  2683  			st.intIdx = 1
  2684  			st.floatIdx++
  2685  		case info.size == 4 && st.intIdx == 1:
  2686  			loc.Regs = []string{"F14"}
  2687  			st.intIdx = 2
  2688  			st.floatIdx++
  2689  			st.fprsDisabled = true
  2690  		case info.size == 4 && st.intIdx == 2:
  2691  			loc.Regs = []string{"F14"}
  2692  			st.intIdx = 3
  2693  			st.floatIdx++
  2694  			st.fprsDisabled = true
  2695  		case info.size == 8 && st.intIdx == 0:
  2696  			loc.Regs = []string{"F12"}
  2697  			st.intIdx = 2
  2698  			st.floatIdx++
  2699  		case info.size == 8 && st.intIdx == 2:
  2700  			loc.Regs = []string{"F14"}
  2701  			st.intIdx = 4
  2702  			st.floatIdx++
  2703  			st.fprsDisabled = true
  2704  		default:
  2705  			st.fprsDisabled = true
  2706  		}
  2707  	}
  2708  	if len(loc.Regs) == 0 {
  2709  		st.fprsDisabled = true
  2710  		loc.IsFloat = false
  2711  		if st.intIdx+nWords <= len(cfg.IntRegs) {
  2712  			loc.Regs = slices.Clone(cfg.IntRegs[st.intIdx : st.intIdx+nWords])
  2713  			st.intIdx += nWords
  2714  		} else if st.intIdx < len(cfg.IntRegs) && info.composite {
  2715  			// MIPS O32: aggregates starting in R4..R7 split across remaining GPRs and 16(R29)+.
  2716  			loc.Regs = slices.Clone(cfg.IntRegs[st.intIdx:])
  2717  			regBytes := int64(len(loc.Regs)) * 4
  2718  			stackBytes := info.size - regBytes
  2719  			st.intIdx = len(cfg.IntRegs)
  2720  			loc.StackOff = st.stackOff
  2721  			loc.StackBytes = stackBytes
  2722  			st.stackOff += alignUp(stackBytes, 4)
  2723  		} else {
  2724  			st.intIdx = len(cfg.IntRegs)
  2725  			if need8 {
  2726  				st.stackOff = alignUp(st.stackOff, 8)
  2727  			}
  2728  			loc.StackOff = st.stackOff
  2729  			st.stackOff += int64(nWords) * 4
  2730  		}
  2731  	}
  2732  	return loc
  2733  }
  2734  
  2735  // mips32AssignRet returns _Complex float and _Complex double values in F0
  2736  // and F2 (one per half) with hard float, and in R2, R3 (complex64) or
  2737  // R2..R5 (complex128) with soft float. O32 returns every other composite,
  2738  // including structs of two floats or doubles, through a hidden pointer.
  2739  func mips32AssignRet(cfg *ABIConfig, fn BindingFunc, info typeInfo, st *abiState) RetLoc {
  2740  	if info.isComplex {
  2741  		if len(cfg.FloatRetRegs) >= 2 {
  2742  			return RetLoc{Size: info.size, IsFloat: true, Regs: slices.Clone(cfg.FloatRetRegs[:2])}
  2743  		}
  2744  		if info.size == 8 {
  2745  			return RetLoc{Size: info.size, Regs: []string{"R2", "R3"}}
  2746  		}
  2747  		return RetLoc{Size: info.size, Regs: []string{"R2", "R3", "R4", "R5"}}
  2748  	}
  2749  	return defaultAssignRet(cfg, fn, info, st)
  2750  }
  2751  
  2752  func newMIPS32ABI(arch string, bigEndian bool) *ABIConfig {
  2753  	return &ABIConfig{
  2754  		Arch:                   arch,
  2755  		PtrSize:                4,
  2756  		CLongSize:              4,
  2757  		StackAlign:             8,
  2758  		ShadowSpace:            16,
  2759  		IntRegs:                []string{"R4", "R5", "R6", "R7"},
  2760  		FloatRegs:              []string{"F12", "F14"},
  2761  		IntRetRegs:             []string{"R2", "R3"},
  2762  		FloatRetRegs:           []string{"F0", "F2"},
  2763  		MaxRegStructSize:       0,
  2764  		IndirectRetReg:         "R4",
  2765  		IndirectRetInArg:       true,
  2766  		AssignParam:            mips32AssignParam,
  2767  		AssignRet:              mips32AssignRet,
  2768  		CompositeRegSlots:      hfaCompositeRegSlots,
  2769  		SPReg:                  "R29",
  2770  		CalleeSavedReg:         "R16",
  2771  		TmpReg:                 "R8",
  2772  		TmpReg2:                "R9",
  2773  		IndCallReg:             "R25",
  2774  		LinkReg:                "R31",
  2775  		AsmTmpReg:              "R23",
  2776  		ShadowUsesSlot0:        true,
  2777  		ZeroVal:                "R0",
  2778  		LocalFrameOff:          24,
  2779  		BigEndian:              bigEndian,
  2780  		LeftJustifyBEComposite: bigEndian,
  2781  		StrictAlign:            true,
  2782  		asm: asmOps{
  2783  			mov:   "MOVW",
  2784  			loadB: "MOVB", loadBU: "MOVBU", loadH: "MOVH", loadHU: "MOVHU", loadW: "MOVW", loadWU: "MOVW",
  2785  			storeB: "MOVB", storeH: "MOVH", storeW: "MOVW",
  2786  			fmovS: "MOVF", fmovD: "MOVD",
  2787  			shl: "SLL", shr: "SRL", or: "OR", add: "ADDU", sub: "SUBU",
  2788  			negSubSP: true,
  2789  		},
  2790  		CallSymbol: func(w io.Writer, sym string, _ bool) {
  2791  			// Load $t9 (R25) with target address per MIPS PIC (-mabicalls) ABI.
  2792  			fmt.Fprintf(w, "\tMOVW\t$%s(SB), R25\n", sym)
  2793  			fmt.Fprintf(w, "\tCALL\t(R25)\n")
  2794  		},
  2795  	}
  2796  }
  2797  
  2798  var mipsABI = newMIPS32ABI("mips", true)
  2799  var mipsleABI = newMIPS32ABI("mipsle", false)
  2800  
  2801  // 64-bit PowerPC C calling conventions:
  2802  //   - Linux ELFv2: https://openpowerfoundation.org/specifications/64bitelfabi/
  2803  //   - AIX 64-bit XCOFF: https://www.ibm.com/docs/en/aix/7.3?topic=overview-subroutine-linkage-convention
  2804  
  2805  // ppc64AssignRet returns _Complex float and _Complex double values in F1 and
  2806  // F2 on both ELFv2 and AIX, and ELFv2 homogeneous floating-point aggregates
  2807  // of up to 8 members in F1..F8. AIX returns every other composite through a
  2808  // hidden pointer.
  2809  func ppc64AssignRet(cfg *ABIConfig, fn BindingFunc, info typeInfo, st *abiState) RetLoc {
  2810  	if info.isComplex {
  2811  		return RetLoc{Size: info.size, Regs: slices.Clone(cfg.FloatRetRegs[:2]), IsFloat: true}
  2812  	}
  2813  	if !cfg.HasFuncDesc && info.composite {
  2814  		if _, count, ok := classifyHFAMax(info, 8); ok {
  2815  			return RetLoc{Size: info.size, Regs: slices.Clone(cfg.FloatRetRegs[:count]), IsFloat: true}
  2816  		}
  2817  	}
  2818  	return defaultAssignRet(cfg, fn, info, st)
  2819  }
  2820  
  2821  func ppc64AssignParam(cfg *ABIConfig, _ BindingFunc, _ int, info typeInfo, st *abiState) ParamLoc {
  2822  	if info.size == 0 {
  2823  		return ParamLoc{}
  2824  	}
  2825  	nSlots := (info.size + 7) / 8
  2826  	slot := st.intIdx
  2827  
  2828  	loc := ParamLoc{Size: info.size, IsFloat: info.isFloat}
  2829  	if info.isComplex {
  2830  		// Both ELFv2 and AIX pass _Complex float and _Complex double as two
  2831  		// separate float or double arguments: each part takes the next FPR
  2832  		// and its own doubleword of the parameter save area.
  2833  		elemSz := info.size / 2
  2834  		st.intIdx = slot + 2
  2835  		loc.IsFloat = true
  2836  		switch {
  2837  		case st.floatIdx+2 <= len(cfg.FloatRegs):
  2838  			loc.Regs = slices.Clone(cfg.FloatRegs[st.floatIdx : st.floatIdx+2])
  2839  			st.floatIdx += 2
  2840  		case st.floatIdx < len(cfg.FloatRegs):
  2841  			// The real part takes F13 and the imaginary part the second
  2842  			// doubleword, where a float is right-justified on ELFv2 BE.
  2843  			loc.Regs = []string{cfg.FloatRegs[st.floatIdx]}
  2844  			st.floatIdx = len(cfg.FloatRegs)
  2845  			loc.StackOff = cfg.ShadowSpace + int64(slot+1)*8
  2846  			if elemSz == 4 {
  2847  				loc.StackOff += cfg.complexFloatStackPad()
  2848  			}
  2849  			loc.StackBytes = elemSz
  2850  			st.stackOff = max(st.stackOff, cfg.ShadowSpace+int64(slot+2)*8)
  2851  		default:
  2852  			// ComplexFloatSplitStack places the parts of a complex64 in
  2853  			// separate doublewords.
  2854  			loc.StackOff = cfg.ShadowSpace + int64(slot)*8
  2855  			st.stackOff = max(st.stackOff, loc.StackOff+16)
  2856  		}
  2857  		return loc
  2858  	}
  2859  	if !cfg.HasFuncDesc && info.composite {
  2860  		if elemSz, count, ok := classifyHFAMax(info, 8); ok {
  2861  			st.intIdx = slot + int(nSlots)
  2862  			loc.IsFloat = true
  2863  			if st.floatIdx+count <= len(cfg.FloatRegs) {
  2864  				loc.Regs = slices.Clone(cfg.FloatRegs[st.floatIdx : st.floatIdx+count])
  2865  				st.floatIdx += count
  2866  				return loc
  2867  			}
  2868  			if st.floatIdx < len(cfg.FloatRegs) {
  2869  				avail := len(cfg.FloatRegs) - st.floatIdx
  2870  				loc.Regs = slices.Clone(cfg.FloatRegs[st.floatIdx:])
  2871  				st.floatIdx = len(cfg.FloatRegs)
  2872  				loc.StackOff = cfg.ShadowSpace + int64(slot)*8 + int64(avail)*elemSz
  2873  				loc.StackBytes = int64(count-avail) * elemSz
  2874  				st.stackOff = max(st.stackOff, cfg.ShadowSpace+int64(slot+int(nSlots))*8)
  2875  				return loc
  2876  			}
  2877  			loc.StackOff = cfg.ShadowSpace + int64(slot)*8
  2878  			st.stackOff = max(st.stackOff, loc.StackOff+nSlots*8)
  2879  			return loc
  2880  		}
  2881  	}
  2882  	if !cfg.HasFuncDesc && info.align >= 16 && slot%2 != 0 {
  2883  		// ELFv2 starts an aggregate with 16-byte alignment (other than
  2884  		// a homogeneous floating-point aggregate) at an even doubleword of
  2885  		// the parameter save area, skipping an odd GPR. AIX does not.
  2886  		slot++
  2887  	}
  2888  	st.intIdx = slot + int(nSlots)
  2889  	switch {
  2890  	case info.isFloat && st.floatIdx < len(cfg.FloatRegs):
  2891  		loc.Regs = []string{cfg.FloatRegs[st.floatIdx]}
  2892  		st.floatIdx++
  2893  	case !info.isFloat && slot+int(nSlots) <= len(cfg.IntRegs):
  2894  		loc.Regs = slices.Clone(cfg.IntRegs[slot : slot+int(nSlots)])
  2895  	case !info.isFloat && slot < len(cfg.IntRegs) && info.composite:
  2896  		// Split aggregate straddling R3..R10 and the parameter save area.
  2897  		loc.Regs = slices.Clone(cfg.IntRegs[slot:])
  2898  		regBytes := int64(len(loc.Regs)) * 8
  2899  		loc.StackOff = cfg.ShadowSpace + int64(len(cfg.IntRegs))*8
  2900  		loc.StackBytes = info.size - regBytes
  2901  		st.stackOff = max(st.stackOff, cfg.ShadowSpace+int64(slot+int(nSlots))*8)
  2902  	default:
  2903  		loc.StackOff = cfg.ShadowSpace + int64(slot)*8
  2904  		st.stackOff = max(st.stackOff, loc.StackOff+nSlots*8)
  2905  	}
  2906  	return loc
  2907  }
  2908  
  2909  func newPPC64ABI(arch string, bigEndian bool, shadowSpace int64, isAIX bool) *ABIConfig {
  2910  	emitAIXDescCall := func(w io.Writer, descSrc string) {
  2911  		fmt.Fprintf(w, "\tMOVD\tR2, 40(R1)\n")
  2912  		fmt.Fprintf(w, "\tMOVD\t%s, R12\n", descSrc)
  2913  		fmt.Fprintf(w, "\tMOVD\t0(R12), R0\n")
  2914  		fmt.Fprintf(w, "\tMOVD\t8(R12), R2\n")
  2915  		fmt.Fprintf(w, "\tMOVD\tR0, CTR\n")
  2916  		fmt.Fprintf(w, "\tBL\t(CTR)\n")
  2917  		fmt.Fprintf(w, "\tMOVD\t40(R1), R2\n")
  2918  		fmt.Fprintf(w, "\tXOR\tR0, R0\n")
  2919  	}
  2920  	maxRegStructSize := int64(16)
  2921  	floatRetRegs := []string{"F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8"}
  2922  	if isAIX {
  2923  		// AIX returns every composite except _Complex float and
  2924  		// _Complex double through a hidden pointer.
  2925  		maxRegStructSize = 0
  2926  		floatRetRegs = []string{"F1", "F2"}
  2927  	}
  2928  	localFrameOff := shadowSpace + 64
  2929  	return &ABIConfig{
  2930  		Arch:                   arch,
  2931  		PtrSize:                8,
  2932  		CLongSize:              8,
  2933  		StackAlign:             16,
  2934  		ShadowSpace:            shadowSpace,
  2935  		MinParamSaveArea:       64,
  2936  		IntRegs:                []string{"R3", "R4", "R5", "R6", "R7", "R8", "R9", "R10"},
  2937  		FloatRegs:              []string{"F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12", "F13"},
  2938  		IntRetRegs:             []string{"R3", "R4"},
  2939  		FloatRetRegs:           floatRetRegs,
  2940  		MaxRegStructSize:       maxRegStructSize,
  2941  		IndirectRetReg:         "R3",
  2942  		IndirectRetInArg:       true,
  2943  		AssignParam:            ppc64AssignParam,
  2944  		AssignRet:              ppc64AssignRet,
  2945  		CompositeRegSlots:      hfaCompositeRegSlots,
  2946  		SPReg:                  "R1",
  2947  		CalleeSavedReg:         "R14",
  2948  		TmpReg:                 "R11",
  2949  		TmpReg2:                "R12",
  2950  		ZeroVal:                "R0",
  2951  		LocalFrameOff:          localFrameOff,
  2952  		BigEndian:              bigEndian,
  2953  		LeftJustifyBEComposite: isAIX,
  2954  		LeftJustifyBETrailing:  !isAIX && bigEndian,
  2955  		// ELFv2 BE right-justifies sub-doubleword composites and floats
  2956  		// in their stack doubleword; AIX left-justifies both.
  2957  		RightJustifyBECompositeStack: !isAIX && bigEndian,
  2958  		LeftJustifyBEFloatStack:      isAIX,
  2959  		ComplexFloatSplitStack:       true,
  2960  		HasFuncDesc:                  isAIX,
  2961  		asm: asmOps{
  2962  			mov:   "MOVD",
  2963  			loadB: "MOVB", loadBU: "MOVBZ", loadH: "MOVH", loadHU: "MOVHZ", loadW: "MOVW", loadWU: "MOVWZ",
  2964  			storeB: "MOVB", storeH: "MOVH", storeW: "MOVW",
  2965  			fmovS: "FMOVS", fmovD: "FMOVD",
  2966  			shl: "SLD", shr: "SRD", or: "OR", add: "ADD", sub: "SUB",
  2967  			alignDisp4: true,
  2968  		},
  2969  		TrampolinePrologue: func(w io.Writer, lay FuncLayout) func(io.Writer) {
  2970  			total := lay.StackSize
  2971  			fmt.Fprintf(w, "\tMOVD\tLR, R0\n")
  2972  			fmt.Fprintf(w, "\tMOVD\tR0, 16(R1)\n")
  2973  			emitPPC64AllocBackchain(w, "R11", total)
  2974  			fmt.Fprintf(w, "\tXOR\tR0, R0\n")
  2975  			if !isAIX {
  2976  				fmt.Fprintf(w, "\tMOVD\tR2, 24(R1)\n")
  2977  			}
  2978  			fmt.Fprintf(w, "\tMOVD\tR3, R14\n")
  2979  			return func(w io.Writer) {
  2980  				if !isAIX {
  2981  					fmt.Fprintf(w, "\tMOVD\t24(R1), R2\n")
  2982  				}
  2983  				emitPPC64AddSP(w, total)
  2984  				fmt.Fprintf(w, "\tMOVD\t16(R1), R0\n")
  2985  				fmt.Fprintf(w, "\tMOVD\tR0, LR\n")
  2986  				fmt.Fprintf(w, "\tXOR\tR0, R0\n")
  2987  			}
  2988  		},
  2989  		CallIndirect: func(w io.Writer, base string) {
  2990  			if isAIX {
  2991  				emitAIXDescCall(w, fmt.Sprintf("0(%s)", base))
  2992  				return
  2993  			}
  2994  			fmt.Fprintf(w, "\tMOVD\tR2, 24(R1)\n")
  2995  			fmt.Fprintf(w, "\tMOVD\t0(%s), R12\n", base)
  2996  			fmt.Fprintf(w, "\tMOVD\tR12, CTR\n")
  2997  			fmt.Fprintf(w, "\tBL\t(CTR)\n")
  2998  			fmt.Fprintf(w, "\tMOVD\t24(R1), R2\n")
  2999  			fmt.Fprintf(w, "\tXOR\tR0, R0\n")
  3000  		},
  3001  		CallSymbol: func(w io.Writer, sym string, static bool) {
  3002  			if isAIX {
  3003  				if static {
  3004  					emitAIXDescCall(w, fmt.Sprintf("$%s(SB)", sym))
  3005  				} else {
  3006  					emitAIXDescCall(w, fmt.Sprintf("__cgo_imp_%s(SB)", sym))
  3007  				}
  3008  				return
  3009  			}
  3010  			fmt.Fprintf(w, "\tBL\t%s(SB)\n", sym)
  3011  			fmt.Fprintf(w, "\tWORD\t$0x60000000\n")
  3012  			fmt.Fprintf(w, "\tXOR\tR0, R0\n")
  3013  		},
  3014  		CallbackPrologue: func(w io.Writer, frameSize int64) int64 {
  3015  			inner := localFrameOff + frameSize
  3016  			total := inner + 16
  3017  			fmt.Fprintf(w, "\tMOVD\tLR, R12\n")
  3018  			fmt.Fprintf(w, "\tMOVD\tR12, 16(R1)\n")
  3019  			if total <= 32760 {
  3020  				emitPPC64AllocBackchain(w, "R12", total)
  3021  				fmt.Fprintf(w, "\tMOVD\tR31, %d(R1)\n", inner)
  3022  				fmt.Fprintf(w, "\tMOVD\tR2, %d(R1)\n", inner+8)
  3023  				fmt.Fprintf(w, "\tXOR\tR0, R0\n")
  3024  				return total
  3025  			}
  3026  			// For total > 32760, large store offsets clobber REGTMP (R31)
  3027  			// before it is saved (and on GOPPC64 < 10, MOVD R31, largeOff(R1)
  3028  			// self-clobbers R31). Allocate an outer 16-byte frame to save R31
  3029  			// and R2 at small displacements before allocating the inner frame.
  3030  			fmt.Fprintf(w, "\tMOVD\tR1, R12\n")
  3031  			fmt.Fprintf(w, "\tADD\t$-16, R1\n")
  3032  			fmt.Fprintf(w, "\tMOVD\tR31, 0(R1)\n")
  3033  			fmt.Fprintf(w, "\tMOVD\tR2, 8(R1)\n")
  3034  			fmt.Fprintf(w, "\tXOR\tR0, R0\n")
  3035  			emitPPC64AddSP(w, -inner)
  3036  			fmt.Fprintf(w, "\tMOVD\tR12, 0(R1)\n")
  3037  			return total
  3038  		},
  3039  		CallbackEpilogue: func(w io.Writer, frameSize int64, _ bool) {
  3040  			inner := localFrameOff + frameSize
  3041  			total := inner + 16
  3042  			if total <= 32760 {
  3043  				fmt.Fprintf(w, "\tMOVD\t%d(R1), R2\n", inner+8)
  3044  				fmt.Fprintf(w, "\tMOVD\t%d(R1), R31\n", inner)
  3045  				fmt.Fprintf(w, "\tADD\t$%d, R1\n", total)
  3046  				fmt.Fprintf(w, "\tMOVD\t16(R1), R12\n")
  3047  				fmt.Fprintf(w, "\tMOVD\tR12, LR\n")
  3048  				fmt.Fprintf(w, "\tRET\n")
  3049  				return
  3050  			}
  3051  			// Re-zero R0 and undo the inner SP adjustment before restoring
  3052  			// R2, R31, and the outer 16-byte frame.
  3053  			fmt.Fprintf(w, "\tXOR\tR0, R0\n")
  3054  			emitPPC64AddSP(w, inner)
  3055  			fmt.Fprintf(w, "\tMOVD\t8(R1), R2\n")
  3056  			fmt.Fprintf(w, "\tMOVD\t0(R1), R31\n")
  3057  			fmt.Fprintf(w, "\tADD\t$16, R1\n")
  3058  			fmt.Fprintf(w, "\tMOVD\t16(R1), R12\n")
  3059  			fmt.Fprintf(w, "\tMOVD\tR12, LR\n")
  3060  			fmt.Fprintf(w, "\tRET\n")
  3061  		},
  3062  	}
  3063  }
  3064  
  3065  var ppc64leABI = newPPC64ABI("ppc64le", false, 32, false)
  3066  var ppc64ABI = newPPC64ABI("ppc64", true, 32, false)
  3067  var aixPPC64ABI = newPPC64ABI("ppc64", true, 48, true)
  3068  
  3069  // IBM Z (s390x) 64-bit ELF C calling convention:
  3070  // "ELF ABI s390x Supplement", Section 1.2: https://github.com/IBM/s390x-abi
  3071  //
  3072  // Summary:
  3073  //   - Integer and pointer arguments use R2..R6; float and double arguments
  3074  //     use F0, F2, F4, F6. Later arguments go in 8-byte stack slots above the
  3075  //     160-byte register save area, right-justified.
  3076  //   - A struct of 1, 2, 4, or 8 bytes is passed in a GPR, except that a
  3077  //     struct whose only member is a float or double (or such a struct) is
  3078  //     passed in an FPR. Arrays (including a one-member array of float), and
  3079  //     unions are not such structs.
  3080  //   - Every other composite, including _Complex float and _Complex double,
  3081  //     is passed by reference to a caller-made copy.
  3082  //   - Every composite is returned through a hidden pointer in R2.
  3083  
  3084  // s390xRegStructSize reports whether a struct or union of size bytes is
  3085  // passed by value in a register under the s390x ELF ABI.
  3086  func s390xRegStructSize(size int64) bool {
  3087  	return size == 1 || size == 2 || size == 4 || size == 8
  3088  }
  3089  
  3090  func s390xAssignParam(cfg *ABIConfig, _ BindingFunc, _ int, info typeInfo, st *abiState) ParamLoc {
  3091  	if info.size == 0 {
  3092  		return ParamLoc{}
  3093  	}
  3094  	if info.isFloat {
  3095  		return cfg.assignFloatParam(info, st)
  3096  	}
  3097  	if info.composite {
  3098  		if info.isComplex || !s390xRegStructSize(info.size) {
  3099  			return cfg.assignPtrParam(info.size, st)
  3100  		}
  3101  		if info.singleFloatStruct && (info.size == 4 || info.size == 8) {
  3102  			return cfg.assignFloatParam(info, st)
  3103  		}
  3104  	}
  3105  	return cfg.assignIntParam(info, st)
  3106  }
  3107  
  3108  var s390xABI = &ABIConfig{
  3109  	Arch:                         "s390x",
  3110  	PtrSize:                      8,
  3111  	CLongSize:                    8,
  3112  	StackAlign:                   8,
  3113  	ShadowSpace:                  160,
  3114  	IntRegs:                      []string{"R2", "R3", "R4", "R5", "R6"},
  3115  	FloatRegs:                    []string{"F0", "F2", "F4", "F6"},
  3116  	IntRetRegs:                   []string{"R2"},
  3117  	FloatRetRegs:                 []string{"F0"},
  3118  	MaxRegStructSize:             0,
  3119  	IndirectRetReg:               "R2",
  3120  	IndirectRetInArg:             true,
  3121  	AssignParam:                  s390xAssignParam,
  3122  	AssignRet:                    defaultAssignRet,
  3123  	SPReg:                        "R15",
  3124  	CalleeSavedReg:               "R8",
  3125  	TmpReg:                       "R1",
  3126  	TmpReg2:                      "R9",
  3127  	LinkReg:                      "R14",
  3128  	ZeroVal:                      "$0",
  3129  	LocalFrameOff:                160,
  3130  	BigEndian:                    true,
  3131  	RightJustifyBECompositeStack: true,
  3132  	asm: asmOps{
  3133  		mov:   "MOVD",
  3134  		loadB: "MOVB", loadBU: "MOVBZ", loadH: "MOVH", loadHU: "MOVHZ", loadW: "MOVW", loadWU: "MOVWZ",
  3135  		storeB: "MOVB", storeH: "MOVH", storeW: "MOVW",
  3136  		fmovS: "FMOVS", fmovD: "FMOVD",
  3137  		shl: "SLD", shr: "SRD", or: "OR", add: "ADD", sub: "SUB",
  3138  		twoOpALU: true,
  3139  		negSubSP: true,
  3140  	},
  3141  	CallbackPrologue: func(w io.Writer, frameSize int64) int64 {
  3142  		total := 160 + frameSize
  3143  		fmt.Fprintf(w, "\tSTMG\tR6, R14, 48(R15)\n")
  3144  		fmt.Fprintf(w, "\tMOVD\tR14, -%d(R15)\n", total)
  3145  		fmt.Fprintf(w, "\tADD\t$-%d, R15\n", total)
  3146  		fmt.Fprintf(w, "\tMOVD\tR14, 0(R15)\n")
  3147  		return total
  3148  	},
  3149  	CallbackEpilogue: func(w io.Writer, frameSize int64, _ bool) {
  3150  		total := 160 + frameSize
  3151  		fmt.Fprintf(w, "\tMOVD\t0(R15), R14\n")
  3152  		fmt.Fprintf(w, "\tADD\t$%d, R15\n", total)
  3153  		fmt.Fprintf(w, "\tLMG\t48(R15), R6, R14\n")
  3154  		fmt.Fprintf(w, "\tRET\n")
  3155  	},
  3156  }
  3157  
  3158  // RISC-V RV64GC and LoongArch64 LP64D C calling conventions:
  3159  //   - RISC-V: https://github.com/riscv-non-isa/riscv-elf-psabi-doc/blob/master/riscv-cc.adoc
  3160  //   - LoongArch64: https://loongson.github.io/LoongArch-Documentation/LoongArch-ELF-ABI-EN.html
  3161  
  3162  // classifyLP64DStruct classifies a <=16-byte composite per the LP64D hardware
  3163  // floating-point calling convention (1-2 FP fields, or 1 FP + 1 integer field).
  3164  //
  3165  // Only structs (including structs with array members) and complex numbers
  3166  // are eligible; unions, represented as arrays, are not.
  3167  func classifyLP64DStruct(info typeInfo) (fields []leafField, nFP, nInt int, ok bool) {
  3168  	if (!info.isStruct && !info.isComplex) || !info.fieldsOK || info.size <= 0 || info.size > 16 {
  3169  		return nil, 0, 0, false
  3170  	}
  3171  	if len(info.fields) < 1 || len(info.fields) > 2 {
  3172  		return nil, 0, 0, false
  3173  	}
  3174  	for _, f := range info.fields {
  3175  		if f.isFloat {
  3176  			nFP++
  3177  		} else {
  3178  			nInt++
  3179  		}
  3180  	}
  3181  	if nFP == 0 {
  3182  		return nil, 0, 0, false
  3183  	}
  3184  	return info.fields, nFP, nInt, true
  3185  }
  3186  
  3187  func lp64dAssignRet(cfg *ABIConfig, fn BindingFunc, info typeInfo, st *abiState) RetLoc {
  3188  	if fields, _, _, ok := classifyLP64DStruct(info); ok {
  3189  		regs := make([]string, len(fields))
  3190  		fpIdx, intIdx := 0, 0
  3191  		for k, f := range fields {
  3192  			if f.isFloat {
  3193  				regs[k] = cfg.FloatRetRegs[fpIdx]
  3194  				fpIdx++
  3195  			} else {
  3196  				regs[k] = cfg.IntRetRegs[intIdx]
  3197  				intIdx++
  3198  			}
  3199  		}
  3200  		return RetLoc{Size: info.size, IsFloat: true, Regs: regs}
  3201  	}
  3202  	return defaultAssignRet(cfg, fn, info, st)
  3203  }
  3204  
  3205  func lp64dCompositeRegSlots(cfg *ABIConfig, info typeInfo, isFloat bool, regs []string) ([]regSlot, bool) {
  3206  	if !isFloat || !info.fieldsOK || len(info.fields) != len(regs) {
  3207  		return nil, false
  3208  	}
  3209  	slots := make([]regSlot, len(regs))
  3210  	for k, f := range info.fields {
  3211  		slots[k] = regSlot{
  3212  			reg:     regs[k],
  3213  			offset:  f.offset,
  3214  			size:    f.size,
  3215  			align:   f.align,
  3216  			isFloat: f.isFloat,
  3217  			signed:  !f.isFloat && (f.signed || (cfg.SignExtUint32 && f.size == 4)),
  3218  		}
  3219  	}
  3220  	return slots, true
  3221  }
  3222  
  3223  func lp64dAssignParam(cfg *ABIConfig, _ BindingFunc, _ int, info typeInfo, st *abiState) ParamLoc {
  3224  	if info.size == 0 {
  3225  		return ParamLoc{}
  3226  	}
  3227  	if info.isFloat {
  3228  		if st.floatIdx < len(cfg.FloatRegs) {
  3229  			return cfg.assignFloatParam(info, st)
  3230  		}
  3231  		if st.intIdx < len(cfg.IntRegs) {
  3232  			reg := cfg.IntRegs[st.intIdx]
  3233  			st.intIdx++
  3234  			return ParamLoc{Size: info.size, Regs: []string{reg}}
  3235  		}
  3236  		return cfg.assignStackParam(info.size, true, st)
  3237  	}
  3238  	if info.composite {
  3239  		if fields, nFP, nInt, ok := classifyLP64DStruct(info); ok &&
  3240  			st.floatIdx+nFP <= len(cfg.FloatRegs) && st.intIdx+nInt <= len(cfg.IntRegs) {
  3241  			regs := make([]string, len(fields))
  3242  			for k, f := range fields {
  3243  				if f.isFloat {
  3244  					regs[k] = cfg.FloatRegs[st.floatIdx]
  3245  					st.floatIdx++
  3246  				} else {
  3247  					regs[k] = cfg.IntRegs[st.intIdx]
  3248  					st.intIdx++
  3249  				}
  3250  			}
  3251  			return ParamLoc{Size: info.size, IsFloat: true, Regs: regs}
  3252  		}
  3253  		if info.size > cfg.MaxRegStructSize {
  3254  			return cfg.assignPtrParam(info.size, st)
  3255  		}
  3256  	}
  3257  	// Unlike variadic arguments, named arguments with 2*XLEN alignment do
  3258  	// not skip to an even register.
  3259  	numRegs := int((info.size + cfg.PtrSize - 1) / cfg.PtrSize)
  3260  	if st.intIdx+numRegs <= len(cfg.IntRegs) {
  3261  		regs := slices.Clone(cfg.IntRegs[st.intIdx : st.intIdx+numRegs])
  3262  		st.intIdx += numRegs
  3263  		return ParamLoc{Size: info.size, Regs: regs}
  3264  	}
  3265  	if st.intIdx < len(cfg.IntRegs) && info.composite {
  3266  		// Split 8B-aligned 9..16B aggregate straddling the last GPR (a7) and stack.
  3267  		regs := slices.Clone(cfg.IntRegs[st.intIdx:])
  3268  		regBytes := int64(len(regs)) * cfg.PtrSize
  3269  		stackBytes := info.size - regBytes
  3270  		st.intIdx = len(cfg.IntRegs)
  3271  		off := st.stackOff
  3272  		st.stackOff += alignUp(stackBytes, cfg.PtrSize)
  3273  		return ParamLoc{Size: info.size, Regs: regs, StackOff: off, StackBytes: stackBytes}
  3274  	}
  3275  	st.intIdx = len(cfg.IntRegs)
  3276  	if info.align >= 16 {
  3277  		st.stackOff = alignUp(st.stackOff, 16)
  3278  	}
  3279  	return cfg.assignStackParam(info.size, false, st)
  3280  }
  3281  
  3282  var riscv64ABI = &ABIConfig{
  3283  	Arch:              "riscv64",
  3284  	PtrSize:           8,
  3285  	CLongSize:         8,
  3286  	StackAlign:        16,
  3287  	IntRegs:           []string{"X10", "X11", "X12", "X13", "X14", "X15", "X16", "X17"},
  3288  	FloatRegs:         []string{"F10", "F11", "F12", "F13", "F14", "F15", "F16", "F17"},
  3289  	IntRetRegs:        []string{"X10", "X11"},
  3290  	FloatRetRegs:      []string{"F10", "F11"},
  3291  	MaxRegStructSize:  16,
  3292  	IndirectRetReg:    "X10",
  3293  	IndirectRetInArg:  true,
  3294  	AssignParam:       lp64dAssignParam,
  3295  	AssignRet:         lp64dAssignRet,
  3296  	CompositeRegSlots: lp64dCompositeRegSlots,
  3297  	SPReg:             "X2",
  3298  	CalleeSavedReg:    "X9",
  3299  	TmpReg:            "X5",
  3300  	TmpReg2:           "X6",
  3301  	IndCallReg:        "X6", // Use T1 (X6) instead of T0 (X5) so JALR X1, (reg) does not trigger a RAS pop+push.
  3302  	LinkReg:           "X1",
  3303  	LRReserve:         16,
  3304  	ZeroVal:           "X0",
  3305  	LocalFrameOff:     16,
  3306  	SignExtUint32:     true,
  3307  	asm: asmOps{
  3308  		mov:   "MOV",
  3309  		loadB: "MOVB", loadBU: "MOVBU", loadH: "MOVH", loadHU: "MOVHU", loadW: "MOVW", loadWU: "MOVWU",
  3310  		storeB: "MOVB", storeH: "MOVH", storeW: "MOVW",
  3311  		fmovS: "MOVF", fmovD: "MOVD",
  3312  		shl: "SLL", shr: "SRL", or: "OR", add: "ADD", sub: "SUB",
  3313  		negSubSP: true,
  3314  	},
  3315  }
  3316  
  3317  var loong64ABI = &ABIConfig{
  3318  	Arch:              "loong64",
  3319  	PtrSize:           8,
  3320  	CLongSize:         8,
  3321  	StackAlign:        16,
  3322  	IntRegs:           []string{"R4", "R5", "R6", "R7", "R8", "R9", "R10", "R11"},
  3323  	FloatRegs:         []string{"F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7"},
  3324  	IntRetRegs:        []string{"R4", "R5"},
  3325  	FloatRetRegs:      []string{"F0", "F1"},
  3326  	MaxRegStructSize:  16,
  3327  	IndirectRetReg:    "R4",
  3328  	IndirectRetInArg:  true,
  3329  	AssignParam:       lp64dAssignParam,
  3330  	AssignRet:         lp64dAssignRet,
  3331  	CompositeRegSlots: lp64dCompositeRegSlots,
  3332  	SPReg:             "R3",
  3333  	CalleeSavedReg:    "R23",
  3334  	TmpReg:            "R12",
  3335  	TmpReg2:           "R13",
  3336  	LinkReg:           "R1",
  3337  	AsmTmpReg:         "R30",
  3338  	LRReserve:         16,
  3339  	ZeroVal:           "R0",
  3340  	LocalFrameOff:     16,
  3341  	SignExtUint32:     true,
  3342  	asm: asmOps{
  3343  		mov:   "MOVV",
  3344  		loadB: "MOVB", loadBU: "MOVBU", loadH: "MOVH", loadHU: "MOVHU", loadW: "MOVW", loadWU: "MOVWU",
  3345  		storeB: "MOVB", storeH: "MOVH", storeW: "MOVW",
  3346  		fmovS: "MOVF", fmovD: "MOVD",
  3347  		shl: "SLLV", shr: "SRLV", or: "OR", add: "ADDV", sub: "SUBV",
  3348  		negSubSP: true,
  3349  	},
  3350  }
  3351  
  3352  // 64-bit MIPS N64 C calling convention:
  3353  // "MIPSpro N32 ABI Handbook", Chapter 2 (SGI Document 007-2816-004).
  3354  
  3355  // classifyMIPS64FPRet reports whether a composite is returned in F0 and F2
  3356  // under N64 with hard float: _Complex float and _Complex double, and structs
  3357  // whose only members are one or two floats or doubles. Arrays, nested
  3358  // structs, and unions are returned in GPRs, even if they contain only
  3359  // floating-point values.
  3360  func classifyMIPS64FPRet(info typeInfo) ([]leafField, bool) {
  3361  	if !info.composite || !info.fieldsOK || info.size <= 0 || info.size > 16 || len(info.fields) < 1 || len(info.fields) > 2 {
  3362  		return nil, false
  3363  	}
  3364  	if info.isComplex {
  3365  		return info.fields, len(info.fields) == 2
  3366  	}
  3367  	if !info.isStruct || len(info.fields) != info.directFields || info.fields[0].offset != 0 {
  3368  		return nil, false
  3369  	}
  3370  	for _, f := range info.fields {
  3371  		if !f.direct || !f.isFloat {
  3372  			return nil, false
  3373  		}
  3374  	}
  3375  	return info.fields, true
  3376  }
  3377  
  3378  // mips64StructSlotIsDouble reports whether the 8-byte slot at offset off of
  3379  // a struct argument holds a double member of the struct itself, which N64
  3380  // passes in an FPR. Doubles in arrays, nested structs, or unions are passed
  3381  // in GPRs.
  3382  func mips64StructSlotIsDouble(info typeInfo, off int64) bool {
  3383  	if !info.isStruct || !info.fieldsOK {
  3384  		return false
  3385  	}
  3386  	for _, f := range info.fields {
  3387  		if f.direct && f.offset == off && f.isFloat && f.size == 8 {
  3388  			return true
  3389  		}
  3390  	}
  3391  	return false
  3392  }
  3393  
  3394  func mips64AssignRet(cfg *ABIConfig, fn BindingFunc, info typeInfo, st *abiState) RetLoc {
  3395  	if fields, ok := classifyMIPS64FPRet(info); ok {
  3396  		if len(cfg.FloatRetRegs) >= len(fields) {
  3397  			return RetLoc{Size: info.size, IsFloat: true, Regs: slices.Clone(cfg.FloatRetRegs[:len(fields)])}
  3398  		}
  3399  		if info.isComplex {
  3400  			// With soft float, each part of a complex number is
  3401  			// returned in its own GPR.
  3402  			return RetLoc{Size: info.size, IsFloat: true, Regs: []string{"R2", "R3"}}
  3403  		}
  3404  	}
  3405  	return defaultAssignRet(cfg, fn, info, st)
  3406  }
  3407  
  3408  // mips64CompositeRegSlots maps each member of a composite returned in F0 and
  3409  // F2 (or R2 and R3 with soft float), or of a complex argument passed in two
  3410  // consecutive FPRs (or GPRs with soft float), to its register.
  3411  func mips64CompositeRegSlots(cfg *ABIConfig, info typeInfo, isFloat bool, regs []string) ([]regSlot, bool) {
  3412  	if !isFloat || len(regs) == 0 {
  3413  		return nil, false
  3414  	}
  3415  	fields, ok := classifyMIPS64FPRet(info)
  3416  	if !ok || len(fields) != len(regs) {
  3417  		return nil, false
  3418  	}
  3419  	slots := make([]regSlot, len(regs))
  3420  	for k, f := range fields {
  3421  		fl := cfg.isFloatReg(regs[k])
  3422  		slots[k] = regSlot{reg: regs[k], offset: f.offset, size: f.size, align: f.align, isFloat: fl, signed: !fl && cfg.SignExtUint32 && f.size == 4}
  3423  	}
  3424  	return slots, true
  3425  }
  3426  
  3427  func mips64AssignParam(cfg *ABIConfig, _ BindingFunc, _ int, info typeInfo, st *abiState) ParamLoc {
  3428  	if info.size == 0 {
  3429  		return ParamLoc{}
  3430  	}
  3431  	slot := st.intIdx
  3432  	if info.isComplex && slot+2 <= len(cfg.IntRegs) {
  3433  		// N64 passes the parts of _Complex float and _Complex double
  3434  		// like two float or double arguments, in two consecutive FPRs (or
  3435  		// GPRs with soft float). In the last argument slot, a complex
  3436  		// number is passed like a struct instead, in R11 and the stack.
  3437  		st.intIdx = slot + 2
  3438  		if len(cfg.FloatRegs) > 0 {
  3439  			st.floatIdx += 2
  3440  			return ParamLoc{Size: info.size, IsFloat: true, Regs: []string{cfg.FloatRegs[slot], cfg.FloatRegs[slot+1]}}
  3441  		}
  3442  		return ParamLoc{Size: info.size, IsFloat: true, Regs: []string{cfg.IntRegs[slot], cfg.IntRegs[slot+1]}}
  3443  	}
  3444  	if info.isFloat {
  3445  		st.intIdx = slot + 1
  3446  		if slot < len(cfg.IntRegs) {
  3447  			if len(cfg.FloatRegs) > 0 {
  3448  				st.floatIdx++
  3449  				return ParamLoc{Size: info.size, IsFloat: true, Regs: []string{cfg.FloatRegs[slot]}}
  3450  			}
  3451  			return ParamLoc{Size: info.size, Regs: []string{cfg.IntRegs[slot]}}
  3452  		}
  3453  		return cfg.assignStackParam(info.size, true, st)
  3454  	}
  3455  	if info.align >= 16 && slot < len(cfg.IntRegs) && slot%2 != 0 {
  3456  		slot++
  3457  	}
  3458  	nSlots := (info.size + 7) / 8
  3459  	if slot < len(cfg.IntRegs) {
  3460  		nReg := min(int(nSlots), len(cfg.IntRegs)-slot)
  3461  		regs := make([]string, nReg)
  3462  		for k := range nReg {
  3463  			if len(cfg.FloatRegs) > 0 && mips64StructSlotIsDouble(info, int64(k)*8) {
  3464  				regs[k] = cfg.FloatRegs[slot+k]
  3465  			} else {
  3466  				regs[k] = cfg.IntRegs[slot+k]
  3467  			}
  3468  		}
  3469  		if slot+int(nSlots) <= len(cfg.IntRegs) {
  3470  			st.intIdx = slot + int(nSlots)
  3471  			return ParamLoc{Size: info.size, Regs: regs}
  3472  		}
  3473  		// Split aggregate straddling R[slot]..R11 / F[12+slot]..F19 and stack.
  3474  		regBytes := int64(nReg) * 8
  3475  		stackBytes := info.size - regBytes
  3476  		st.intIdx = len(cfg.IntRegs)
  3477  		off := st.stackOff
  3478  		st.stackOff += alignUp(stackBytes, 8)
  3479  		return ParamLoc{Size: info.size, Regs: regs, StackOff: off, StackBytes: stackBytes}
  3480  	}
  3481  	st.intIdx = len(cfg.IntRegs)
  3482  	if info.align >= 16 {
  3483  		st.stackOff = alignUp(st.stackOff, 16)
  3484  	}
  3485  	return cfg.assignStackParam(info.size, false, st)
  3486  }
  3487  
  3488  func newMIPS64ABI(arch string, bigEndian bool) *ABIConfig {
  3489  	return &ABIConfig{
  3490  		Arch:                   arch,
  3491  		PtrSize:                8,
  3492  		CLongSize:              8,
  3493  		StackAlign:             16,
  3494  		IntRegs:                []string{"R4", "R5", "R6", "R7", "R8", "R9", "R10", "R11"},
  3495  		FloatRegs:              []string{"F12", "F13", "F14", "F15", "F16", "F17", "F18", "F19"},
  3496  		IntRetRegs:             []string{"R2", "R3"},
  3497  		FloatRetRegs:           []string{"F0", "F2"},
  3498  		MaxRegStructSize:       16,
  3499  		IndirectRetReg:         "R4",
  3500  		IndirectRetInArg:       true,
  3501  		AssignParam:            mips64AssignParam,
  3502  		AssignRet:              mips64AssignRet,
  3503  		CompositeRegSlots:      mips64CompositeRegSlots,
  3504  		SPReg:                  "R29",
  3505  		CalleeSavedReg:         "R16",
  3506  		TmpReg:                 "R12",
  3507  		TmpReg2:                "R13",
  3508  		IndCallReg:             "R25",
  3509  		LinkReg:                "R31",
  3510  		LRReserve:              16,
  3511  		ZeroVal:                "R0",
  3512  		LocalFrameOff:          16,
  3513  		BigEndian:              bigEndian,
  3514  		LeftJustifyBEComposite: bigEndian,
  3515  		// N64 left-justifies a float in its stack slot on big-endian
  3516  		// targets, and sign-extends uint32 values to 64 bits.
  3517  		LeftJustifyBEFloatStack: bigEndian,
  3518  		SignExtUint32:           true,
  3519  		StrictAlign:             true,
  3520  		asm: asmOps{
  3521  			mov:   "MOVV",
  3522  			loadB: "MOVB", loadBU: "MOVBU", loadH: "MOVH", loadHU: "MOVHU", loadW: "MOVW", loadWU: "MOVWU",
  3523  			storeB: "MOVB", storeH: "MOVH", storeW: "MOVW",
  3524  			fmovS: "MOVF", fmovD: "MOVD",
  3525  			shl: "SLLV", shr: "SRLV", or: "OR", add: "ADDV", sub: "SUBV",
  3526  			negSubSP: true,
  3527  		},
  3528  		CallSymbol: func(w io.Writer, sym string, _ bool) {
  3529  			// Load $t9 (R25) with target address per MIPS64 PIC (-mabicalls) ABI.
  3530  			fmt.Fprintf(w, "\tMOVV\t$%s(SB), R25\n", sym)
  3531  			fmt.Fprintf(w, "\tCALL\t(R25)\n")
  3532  		},
  3533  		CallbackPrologue: func(w io.Writer, frameSize int64) int64 {
  3534  			// Save C callee-saved R23 (REGTMP) and RSB (R28/$gp), then initialize
  3535  			// RSB = PC & 0xffffffff00000000 for Go (SB) addressing.
  3536  			total := 32 + frameSize
  3537  			if total <= 32760 {
  3538  				fmt.Fprintf(w, "\tMOVV\tR31, -%d(R29)\n", total)
  3539  				fmt.Fprintf(w, "\tADDV\t$-%d, R29\n", total)
  3540  				fmt.Fprintf(w, "\tMOVV\tR31, 0(R29)\n")
  3541  				fmt.Fprintf(w, "\tMOVV\tRSB, 8(R29)\n")
  3542  				fmt.Fprintf(w, "\tMOVV\tR23, %d(R29)\n", 16+frameSize)
  3543  			} else {
  3544  				fmt.Fprintf(w, "\tADDV\t$-16, R29\n")
  3545  				fmt.Fprintf(w, "\tMOVV\tR23, 0(R29)\n")
  3546  				fmt.Fprintf(w, "\tMOVV\tRSB, 8(R29)\n")
  3547  				fmt.Fprintf(w, "\tMOVV\tR31, -%d(R29)\n", 16+frameSize)
  3548  				fmt.Fprintf(w, "\tADDV\t$-%d, R29\n", 16+frameSize)
  3549  				fmt.Fprintf(w, "\tMOVV\tR31, 0(R29)\n")
  3550  			}
  3551  			fmt.Fprintf(w, "\tBGEZAL\tR0, 1(PC)\n")
  3552  			fmt.Fprintf(w, "\tSRLV\t$32, R31, RSB\n")
  3553  			fmt.Fprintf(w, "\tSLLV\t$32, RSB\n")
  3554  			return total
  3555  		},
  3556  		CallbackEpilogue: func(w io.Writer, frameSize int64, _ bool) {
  3557  			total := 32 + frameSize
  3558  			if total <= 32760 {
  3559  				fmt.Fprintf(w, "\tMOVV\t%d(R29), R23\n", 16+frameSize)
  3560  				fmt.Fprintf(w, "\tMOVV\t8(R29), RSB\n")
  3561  				fmt.Fprintf(w, "\tMOVV\t0(R29), R31\n")
  3562  				fmt.Fprintf(w, "\tADDV\t$%d, R29\n", total)
  3563  				fmt.Fprintf(w, "\tRET\n")
  3564  				return
  3565  			}
  3566  			fmt.Fprintf(w, "\tMOVV\t0(R29), R31\n")
  3567  			fmt.Fprintf(w, "\tADDV\t$%d, R29\n", 16+frameSize)
  3568  			fmt.Fprintf(w, "\tMOVV\t8(R29), RSB\n")
  3569  			fmt.Fprintf(w, "\tMOVV\t0(R29), R23\n")
  3570  			fmt.Fprintf(w, "\tADDV\t$16, R29\n")
  3571  			fmt.Fprintf(w, "\tRET\n")
  3572  		},
  3573  	}
  3574  }
  3575  
  3576  var mips64ABI = newMIPS64ABI("mips64", true)
  3577  var mips64leABI = newMIPS64ABI("mips64le", false)
  3578  
  3579  // getABI returns the ABIConfig for the given targetOS/targetArch.
  3580  func getABI(targetOS, targetArch string) *ABIConfig {
  3581  	var cfg ABIConfig
  3582  	switch targetArch {
  3583  	case "amd64":
  3584  		if targetOS == "windows" {
  3585  			cfg = *win64ABI
  3586  		} else {
  3587  			cfg = *amd64ABI
  3588  		}
  3589  	case "arm64":
  3590  		cfg = *arm64ABI
  3591  		switch targetOS {
  3592  		case "darwin", "ios":
  3593  			cfg.PackStackArgs = true
  3594  		case "windows":
  3595  			cfg.CLongSize = 4
  3596  			cfg.IndirectSymCall = true
  3597  		}
  3598  	case "386":
  3599  		cfg = *i386ABI
  3600  		switch targetOS {
  3601  		case "windows":
  3602  			cfg.SysVI386SretPop = false
  3603  			cfg.AssignRet = win32AssignRet
  3604  			cfg.IndirectSymCall = true
  3605  		case "freebsd", "openbsd":
  3606  			cfg.AssignRet = bsd386AssignRet
  3607  		}
  3608  	case "arm":
  3609  		cfg = *armABI
  3610  		if targetOS == "android" || targetOS == "openbsd" || goarmSoftFloat() {
  3611  			cfg.IsFloatReg = nil
  3612  			cfg.LoadFloat = nil
  3613  			cfg.StoreFloat = nil
  3614  			cfg.FloatRegs = nil
  3615  			cfg.FloatRetRegs = nil
  3616  			cfg.AssignRet = defaultAssignRet
  3617  			cfg.CompositeRegSlots = nil
  3618  		}
  3619  	case "riscv64":
  3620  		cfg = *riscv64ABI
  3621  	case "loong64":
  3622  		cfg = *loong64ABI
  3623  	case "ppc64":
  3624  		if targetOS == "aix" {
  3625  			cfg = *aixPPC64ABI
  3626  		} else {
  3627  			cfg = *ppc64ABI
  3628  		}
  3629  	case "ppc64le":
  3630  		cfg = *ppc64leABI
  3631  	case "s390x":
  3632  		cfg = *s390xABI
  3633  	case "mips64", "mips64le":
  3634  		if targetArch == "mips64" {
  3635  			cfg = *mips64ABI
  3636  		} else {
  3637  			cfg = *mips64leABI
  3638  		}
  3639  		if gomips64 := os.Getenv("GOMIPS64"); gomips64 == "softfloat" || (gomips64 == "" && buildcfg.GOMIPS64 == "softfloat") {
  3640  			cfg.FloatRegs = nil
  3641  			cfg.FloatRetRegs = nil
  3642  		}
  3643  	case "mips", "mipsle":
  3644  		if targetArch == "mips" {
  3645  			cfg = *mipsABI
  3646  		} else {
  3647  			cfg = *mipsleABI
  3648  		}
  3649  		if gomips := os.Getenv("GOMIPS"); gomips == "softfloat" || (gomips == "" && buildcfg.GOMIPS == "softfloat") {
  3650  			cfg.FloatRegs = nil
  3651  			cfg.FloatRetRegs = nil
  3652  		}
  3653  	default:
  3654  		panic("unsupported arch: " + targetArch)
  3655  	}
  3656  	cfg.OS = targetOS
  3657  	return &cfg
  3658  }
  3659  

View as plain text