Source file src/cmd/compile/internal/ssa/rewrite.go

     1  // Copyright 2015 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 ssa
     6  
     7  import (
     8  	"encoding/binary"
     9  	"fmt"
    10  	"internal/buildcfg"
    11  	"io"
    12  	"math"
    13  	"math/bits"
    14  	"os"
    15  	"path/filepath"
    16  	"strings"
    17  
    18  	"cmd/compile/internal/base"
    19  	"cmd/compile/internal/logopt"
    20  	"cmd/compile/internal/ssa/ssaop"
    21  	"cmd/compile/internal/types"
    22  	"cmd/internal/obj"
    23  	"cmd/internal/obj/s390x"
    24  	"cmd/internal/objabi"
    25  	"cmd/internal/src"
    26  )
    27  
    28  // Aux is an interface to hold miscellaneous data in Blocks and Values.
    29  type Aux interface {
    30  	CanBeAnSSAAux()
    31  }
    32  
    33  func BoolToAuxInt(b bool) int64 {
    34  	if b {
    35  		return 1
    36  	}
    37  	return 0
    38  }
    39  
    40  // FlagConstant represents the result of a compile-time comparison.
    41  // The sense of these flags does not necessarily represent the hardware's notion
    42  // of a flags register - these are just a compile-time construct.
    43  // We happen to match the semantics to those of arm/arm64.
    44  // Note that these semantics differ from x86: the carry flag has the opposite
    45  // sense on a subtraction!
    46  //
    47  //	On amd64, C=1 represents a borrow, e.g. SBB on amd64 does x - y - C.
    48  //	On arm64, C=0 represents a borrow, e.g. SBC on arm64 does x - y - ^C.
    49  //	 (because it does x + ^y + C).
    50  //
    51  // See https://en.wikipedia.org/wiki/Carry_flag#Vs._borrow_flag
    52  type FlagConstant uint8
    53  
    54  func IsNewObjectCall(aux Aux) bool {
    55  	fn := aux.(*AuxCall).Fn
    56  	return fn != nil && fn.String() == "runtime.newobject"
    57  }
    58  
    59  func IsSpecializedMalloc(aux Aux) bool {
    60  	fn := aux.(*AuxCall).Fn
    61  	if fn == nil {
    62  		return false
    63  	}
    64  	name := fn.String()
    65  	return strings.HasPrefix(name, "runtime.mallocgcSmallNoScanSC") ||
    66  		strings.HasPrefix(name, "runtime.mallocgcSmallScanNoHeaderSC") ||
    67  		strings.HasPrefix(name, "runtime.mallocgcTinySC")
    68  }
    69  
    70  // StringAux wraps string values for use in Aux.
    71  type StringAux string
    72  
    73  func StringToAux(s string) Aux {
    74  	return StringAux(s)
    75  }
    76  
    77  func AuxIntToArm64ConditionalParams(i int64) Arm64ConditionalParams {
    78  	var params Arm64ConditionalParams
    79  	params.Cond = ssaop.Op(i & 0xffff)
    80  	i >>= 16
    81  	params.NzcvVal = uint8(i & 0x0f)
    82  	i >>= 4
    83  	params.ConstVal = uint8(i & 0x1f)
    84  	i >>= 5
    85  	params.Ind = i == 1
    86  	return params
    87  }
    88  
    89  func LogLargeCopy(funcName string, pos src.XPos, s int64) {
    90  	if s < 128 {
    91  		return
    92  	}
    93  	if logopt.Enabled() {
    94  		logopt.LogOpt(pos, "copy", "lower", funcName, fmt.Sprintf("%d bytes", s))
    95  	}
    96  }
    97  
    98  // for now only used to mark moves that need to avoid clobbering flags
    99  type auxMark bool
   100  
   101  var AuxMark auxMark
   102  
   103  // PanicBoundsC contains a constant for a bounds failure.
   104  type PanicBoundsC struct {
   105  	C int64
   106  }
   107  
   108  // PanicBoundsCC contains 2 constants for a bounds failure.
   109  type PanicBoundsCC struct {
   110  	Cx int64
   111  	Cy int64
   112  }
   113  
   114  func GetPPC64Shiftsh(auxint int64) int64 {
   115  	return int64(int8(auxint >> 16))
   116  }
   117  
   118  func GetPPC64Shiftmb(auxint int64) int64 {
   119  	return int64(int8(auxint >> 8))
   120  }
   121  
   122  // DecodePPC64RotateMask is the inverse operation of encodePPC64RotateMask.  The values returned as
   123  // mb and me satisfy the POWER ISA definition of MASK(x,y) where MASK(mb,me) = mask.
   124  func DecodePPC64RotateMask(sauxint int64) (rotate, mb, me int64, mask uint64) {
   125  	auxint := uint64(sauxint)
   126  	rotate = int64((auxint >> 16) & 0xFF)
   127  	mb = int64((auxint >> 8) & 0xFF)
   128  	me = int64((auxint >> 0) & 0xFF)
   129  	nbits := int64((auxint >> 24) & 0xFF)
   130  	mask = ((1 << uint(nbits-mb)) - 1) ^ ((1 << uint(nbits-me)) - 1)
   131  	if mb > me {
   132  		mask = ^mask
   133  	}
   134  	if nbits == 32 {
   135  		mask = uint64(uint32(mask))
   136  	}
   137  
   138  	// Fixup ME to match ISA definition.  The second argument to MASK(..,me)
   139  	// is inclusive.
   140  	me = (me - 1) & (nbits - 1)
   141  	return
   142  }
   143  
   144  // DivisionNeedsFixUp reports whether the division needs fix-up code.
   145  func DivisionNeedsFixUp(v *Value) bool {
   146  	return v.AuxInt == 0
   147  }
   148  
   149  // ZeroUpper32Bits checks if value zeroes out upper 32-bit of 64-bit register.
   150  // depth limits recursion depth. In AMD64.rules 3 is used as limit,
   151  // because it catches same amount of cases as 4.
   152  func ZeroUpper32Bits(x *Value) bool { return zeroUpperBits(x, 32, 3) }
   153  
   154  // zeroUpperBits reports whether the 64-bit register holding x provably has
   155  // its upper `bits` bits zero, i.e. the value is below 2^(64-bits).
   156  //
   157  // Which ops guarantee this is declared per op in the _gen op definitions
   158  // (the zeroUpperBits attribute); only the value-dependent cases live here.
   159  func zeroUpperBits(x *Value, bits int64, depth int) bool {
   160  	if x.Type.IsSigned() && 8*x.Type.Size() <= 64-bits {
   161  		// A spill/restore sign-extends from the type's width (issue 68227).
   162  		// A signed type no wider than the claimed value width may have its
   163  		// sign bit set, so a restore can write ones into the upper bits.
   164  		// Wider signed types are safe: their value is below the type's
   165  		// sign bit, so a restore zero-extends.
   166  		return false
   167  	}
   168  	if int64(ssaop.OpcodeTable[x.Op].ZeroUpperBits) >= bits {
   169  		return true
   170  	}
   171  	switch x.Op {
   172  	case ssaop.OpAMD64MOVQconst, ssaop.OpAMD64MOVLconst:
   173  		// A constant qualifies whenever its value fits the claimed width.
   174  		// (MOVLconst always zeroes the upper 32 bits, so for bits==32 it
   175  		// is already handled by its zeroUpperBits attribute.)
   176  		return uint64(x.AuxInt)>>(64-bits) == 0
   177  	case ssaop.OpArg: // note: but not ArgIntReg
   178  		// amd64 always loads args from the stack unsigned.
   179  		// most other architectures load them sign/zero extended based on the type.
   180  		return 8*x.Type.Size() == 64-bits && x.Block.Func.Config.Arch == "amd64"
   181  	case ssaop.OpSelect0, ssaop.OpSelect1:
   182  		// A Select names one register result of a tuple-producing op, so
   183  		// the question is what that op's write does. The op's attribute
   184  		// covers every integer result; a Select of a non-covered result
   185  		// (flags, memory) never appears as an operand of the rules that
   186  		// ask about upper bits.
   187  		return int64(ssaop.OpcodeTable[x.Args[0].Op].ZeroUpperBits) >= bits
   188  	case ssaop.OpPhi:
   189  		// Phis can use each-other as an arguments, instead of tracking visited values,
   190  		// just limit recursion depth.
   191  		if depth <= 0 {
   192  			return false
   193  		}
   194  		for i := range x.Args {
   195  			if !zeroUpperBits(x.Args[i], bits, depth-1) {
   196  				return false
   197  			}
   198  		}
   199  		return true
   200  	}
   201  	return false
   202  }
   203  
   204  // ZeroUpperVec reports whether the vector register holding x provably has
   205  // all of its bits above x's width zero, so viewing it at a wider width
   206  // zero-extends x.
   207  //
   208  // Which ops guarantee this is declared per op in the _gen op definitions (the
   209  // zeroUpperVec attribute). This holds through spills, restores, and register
   210  // moves only because those use VEX encodings for SIMD values (see
   211  // amd64.avxMove).
   212  func ZeroUpperVec(x *Value) bool { return zeroUpperVec(x, 3) }
   213  
   214  func zeroUpperVec(x *Value, depth int) bool {
   215  	if ssaop.OpcodeTable[x.Op].ZeroUpperVec {
   216  		return true
   217  	}
   218  	switch x.Op {
   219  	case ssaop.OpPhi:
   220  		// As in zeroUpperBits, limit the recursion depth rather than
   221  		// tracking visited values.
   222  		if depth <= 0 {
   223  			return false
   224  		}
   225  		for _, a := range x.Args {
   226  			if !zeroUpperVec(a, depth-1) {
   227  				return false
   228  			}
   229  		}
   230  		return true
   231  	}
   232  	return false
   233  }
   234  
   235  // ZeroUpper48Bits is similar to ZeroUpper32Bits, but for upper 48 bits.
   236  func ZeroUpper48Bits(x *Value) bool { return zeroUpperBits(x, 48, 3) }
   237  
   238  // ZeroUpper56Bits is similar to ZeroUpper32Bits, but for upper 56 bits.
   239  func ZeroUpper56Bits(x *Value) bool { return zeroUpperBits(x, 56, 3) }
   240  
   241  // IsSamePtr reports whether p1 and p2 point to the same address.
   242  func IsSamePtr(p1, p2 *Value) bool {
   243  	if p1 == p2 {
   244  		return true
   245  	}
   246  	if p1.Op != p2.Op {
   247  		for p1.Op == ssaop.OpOffPtr && p1.AuxInt == 0 {
   248  			p1 = p1.Args[0]
   249  		}
   250  		for p2.Op == ssaop.OpOffPtr && p2.AuxInt == 0 {
   251  			p2 = p2.Args[0]
   252  		}
   253  		if p1 == p2 {
   254  			return true
   255  		}
   256  		if p1.Op != p2.Op {
   257  			return false
   258  		}
   259  	}
   260  	switch p1.Op {
   261  	case ssaop.OpOffPtr:
   262  		return p1.AuxInt == p2.AuxInt && IsSamePtr(p1.Args[0], p2.Args[0])
   263  	case ssaop.OpAddr, ssaop.OpLocalAddr:
   264  		return p1.Aux == p2.Aux
   265  	case ssaop.OpAddPtr:
   266  		return p1.Args[1] == p2.Args[1] && IsSamePtr(p1.Args[0], p2.Args[0])
   267  	}
   268  	return false
   269  }
   270  
   271  // Disjoint reports whether the memory region specified by [p1:p1+t1.Size())
   272  // does not overlap with [p2:p2+t2.Size()).
   273  // A return value of false does not imply the regions overlap.
   274  func Disjoint(p1 *Value, t1 *types.Type, p2 *Value, t2 *types.Type) bool {
   275  	return Disjoint1(p1, t1.Size(), p2, t2.Size())
   276  }
   277  
   278  // Disjoint1 reports whether the memory region specified by [p1:p1+n1)
   279  // does not overlap with [p2:p2+n2).
   280  // A return value of false does not imply the regions overlap.
   281  func Disjoint1(p1 *Value, n1 int64, p2 *Value, n2 int64) bool {
   282  	if n1 == 0 || n2 == 0 {
   283  		return true
   284  	}
   285  	if p1 == p2 {
   286  		return false
   287  	}
   288  	baseAndOffset := func(ptr *Value) (base *Value, offset int64) {
   289  		base, offset = ptr, 0
   290  		for base.Op == ssaop.OpOffPtr {
   291  			offset += base.AuxInt
   292  			base = base.Args[0]
   293  		}
   294  		if ssaop.OpcodeTable[base.Op].NilCheck {
   295  			base = base.Args[0]
   296  		}
   297  		return base, offset
   298  	}
   299  
   300  	// Run types-based analysis
   301  	if DisjointTypes(p1.Type, p2.Type) {
   302  		return true
   303  	}
   304  
   305  	p1, off1 := baseAndOffset(p1)
   306  	p2, off2 := baseAndOffset(p2)
   307  	if IsSamePtr(p1, p2) {
   308  		return !Overlap(off1, n1, off2, n2)
   309  	}
   310  	// p1 and p2 are not the same, so if they are both OpAddrs then
   311  	// they point to different variables.
   312  	// If one pointer is on the stack and the other is an argument
   313  	// then they can't overlap.
   314  	switch p1.Op {
   315  	case ssaop.OpAddr, ssaop.OpLocalAddr:
   316  		if p2.Op == ssaop.OpAddr || p2.Op == ssaop.OpLocalAddr || p2.Op == ssaop.OpSP {
   317  			return true
   318  		}
   319  		return (p2.Op == ssaop.OpArg || p2.Op == ssaop.OpArgIntReg) && p1.Args[0].Op == ssaop.OpSP
   320  	case ssaop.OpArg, ssaop.OpArgIntReg:
   321  		if p2.Op == ssaop.OpSP || p2.Op == ssaop.OpLocalAddr {
   322  			return true
   323  		}
   324  	case ssaop.OpSP:
   325  		return p2.Op == ssaop.OpAddr || p2.Op == ssaop.OpLocalAddr || p2.Op == ssaop.OpArg || p2.Op == ssaop.OpArgIntReg || p2.Op == ssaop.OpSP
   326  	}
   327  	return false
   328  }
   329  
   330  // DisjointTypes reports whether a memory region pointed to by a pointer of type
   331  // t1 does not overlap with a memory region pointed to by a pointer of type t2 --
   332  // based on type aliasing rules.
   333  func DisjointTypes(t1 *types.Type, t2 *types.Type) bool {
   334  	// Unsafe pointer can alias with anything.
   335  	if t1.IsUnsafePtr() || t2.IsUnsafePtr() {
   336  		return false
   337  	}
   338  
   339  	if !t1.IsPtr() || !t2.IsPtr() {
   340  		// Treat non-pointer types (such as TFUNC, TMAP, uintptr) conservatively.
   341  		return false
   342  	}
   343  
   344  	t1 = t1.Elem()
   345  	t2 = t2.Elem()
   346  
   347  	// Not-in-heap types are not supported -- they are rare and non-important; also,
   348  	// type.HasPointers check doesn't work for them correctly.
   349  	if t1.NotInHeap() || t2.NotInHeap() {
   350  		return false
   351  	}
   352  
   353  	isPtrShaped := func(t *types.Type) bool { return int(t.Size()) == types.PtrSize && t.HasPointers() }
   354  
   355  	// Pointers and non-pointers are disjoint (https://pkg.go.dev/unsafe#Pointer).
   356  	if (isPtrShaped(t1) && !t2.HasPointers()) ||
   357  		(isPtrShaped(t2) && !t1.HasPointers()) {
   358  		return true
   359  	}
   360  
   361  	return false
   362  }
   363  
   364  // Overlap reports whether the ranges given by the given offset and
   365  // size pairs Overlap.
   366  func Overlap(offset1, size1, offset2, size2 int64) bool {
   367  	if offset1 >= offset2 && offset2+size2 > offset1 {
   368  		return true
   369  	}
   370  	if offset2 >= offset1 && offset1+size1 > offset2 {
   371  		return true
   372  	}
   373  	return false
   374  }
   375  
   376  // isInlinableMemmove reports whether the given arch performs a Move of the given size
   377  // faster than memmove. It will only return true if replacing the memmove with a Move is
   378  // safe, either because Move will do all of its loads before any of its stores, or
   379  // because the arguments are known to be disjoint.
   380  // This is used as a check for replacing memmove with Move ops.
   381  func isInlinableMemmove(dst, src *Value, sz int64, c *Config) bool {
   382  	// It is always safe to convert memmove into Move when its arguments are disjoint.
   383  	// Move ops may or may not be faster for large sizes depending on how the platform
   384  	// lowers them, so we only perform this optimization on platforms that we know to
   385  	// have fast Move ops.
   386  	switch c.Arch {
   387  	case "amd64":
   388  		return sz <= 16 || (sz < 1024 && Disjoint1(dst, sz, src, sz))
   389  	case "arm64":
   390  		return sz <= 64 || (sz <= 1024 && Disjoint1(dst, sz, src, sz))
   391  	case "loong64":
   392  		return sz <= 16 || (sz <= 64 && Disjoint1(dst, sz, src, sz))
   393  	case "386":
   394  		return sz <= 8
   395  	case "s390x", "ppc64", "ppc64le":
   396  		return sz <= 8 || Disjoint1(dst, sz, src, sz)
   397  	case "arm", "mips", "mips64", "mipsle", "mips64le", "riscv64":
   398  		return sz <= 4
   399  	}
   400  	return false
   401  }
   402  
   403  func IsInlinableMemmove(dst, src *Value, sz int64, c *Config) bool {
   404  	return isInlinableMemmove(dst, src, sz, c)
   405  }
   406  
   407  func (auxMark) CanBeAnSSAAux() {}
   408  
   409  func (StringAux) CanBeAnSSAAux() {}
   410  
   411  // returns the Lsb part of the auxInt field of arm64 bitfield ops.
   412  func (bfc Arm64BitField) Lsb() int64 {
   413  	return int64(uint64(bfc) >> 8)
   414  }
   415  
   416  // returns the Width part of the auxInt field of arm64 bitfield ops.
   417  func (bfc Arm64BitField) Width() int64 {
   418  	return int64(bfc) & 0xff
   419  }
   420  
   421  // extracts NZCV flags from auxint.
   422  func (condParams Arm64ConditionalParams) Nzcv() int64 {
   423  	return int64(condParams.NzcvVal)
   424  }
   425  
   426  // extracts constant value from auxint if present.
   427  func (condParams Arm64ConditionalParams) ConstValue() (int64, bool) {
   428  	return int64(condParams.ConstVal), condParams.Ind
   429  }
   430  
   431  // N reports whether the result of an operation is negative (high bit set).
   432  func (fc FlagConstant) N() bool {
   433  	return fc&1 != 0
   434  }
   435  
   436  // Z reports whether the result of an operation is 0.
   437  func (fc FlagConstant) Z() bool {
   438  	return fc&2 != 0
   439  }
   440  
   441  // C reports whether an unsigned add overflowed (carry), or an
   442  // unsigned subtract did not underflow (borrow).
   443  func (fc FlagConstant) C() bool {
   444  	return fc&4 != 0
   445  }
   446  
   447  // V reports whether a signed operation overflowed or underflowed.
   448  func (fc FlagConstant) V() bool {
   449  	return fc&8 != 0
   450  }
   451  
   452  func (fc FlagConstant) Eq() bool {
   453  	return fc.Z()
   454  }
   455  
   456  func (fc FlagConstant) Ne() bool {
   457  	return !fc.Z()
   458  }
   459  
   460  func (fc FlagConstant) Lt() bool {
   461  	return fc.N() != fc.V()
   462  }
   463  
   464  func (fc FlagConstant) Le() bool {
   465  	return fc.Z() || fc.Lt()
   466  }
   467  
   468  func (fc FlagConstant) Gt() bool {
   469  	return !fc.Z() && fc.Ge()
   470  }
   471  
   472  func (fc FlagConstant) Ge() bool {
   473  	return fc.N() == fc.V()
   474  }
   475  
   476  func (fc FlagConstant) Ult() bool {
   477  	return !fc.C()
   478  }
   479  
   480  func (fc FlagConstant) Ule() bool {
   481  	return fc.Z() || fc.Ult()
   482  }
   483  
   484  func (fc FlagConstant) Ugt() bool {
   485  	return !fc.Z() && fc.Uge()
   486  }
   487  
   488  func (fc FlagConstant) Uge() bool {
   489  	return fc.C()
   490  }
   491  
   492  // The noov conditions compare the result of an operation with 0,
   493  // ignoring V, as the MI, PL and EQ conditions that implement them do.
   494  
   495  func (fc FlagConstant) LtNoov() bool {
   496  	return fc.N()
   497  }
   498  
   499  func (fc FlagConstant) LeNoov() bool {
   500  	return fc.Z() || fc.LtNoov()
   501  }
   502  
   503  func (fc FlagConstant) GtNoov() bool {
   504  	return !fc.Z() && fc.GeNoov()
   505  }
   506  
   507  func (fc FlagConstant) GeNoov() bool {
   508  	return !fc.N()
   509  }
   510  
   511  func (fc FlagConstant) String() string {
   512  	return fmt.Sprintf("N=%v,Z=%v,C=%v,V=%v", fc.N(), fc.Z(), fc.C(), fc.V())
   513  }
   514  
   515  func (p PanicBoundsC) CanBeAnSSAAux() {
   516  }
   517  
   518  func (p PanicBoundsCC) CanBeAnSSAAux() {
   519  }
   520  
   521  // AddFlags32 returns the flags that would be set from computing x+y.
   522  func AddFlags32(x, y int32) FlagConstant {
   523  	var fcb FlagConstantBuilder
   524  	fcb.Z = x+y == 0
   525  	fcb.N = x+y < 0
   526  	fcb.C = uint32(x+y) < uint32(x)
   527  	fcb.V = x >= 0 && y >= 0 && x+y < 0 || x < 0 && y < 0 && x+y >= 0
   528  	return fcb.Encode()
   529  }
   530  
   531  // Note: addFlags(x,y) != subFlags(x,-y) in some situations:
   532  //  - the results of the C flag are different
   533  //  - the results of the V flag when y==minint are different
   534  
   535  // AddFlags64 returns the flags that would be set from computing x+y.
   536  func AddFlags64(x, y int64) FlagConstant {
   537  	var fcb FlagConstantBuilder
   538  	fcb.Z = x+y == 0
   539  	fcb.N = x+y < 0
   540  	fcb.C = uint64(x+y) < uint64(x)
   541  	fcb.V = x >= 0 && y >= 0 && x+y < 0 || x < 0 && y < 0 && x+y >= 0
   542  	return fcb.Encode()
   543  }
   544  
   545  func Arm64BitFieldToAuxInt(v Arm64BitField) int64 {
   546  	return int64(v)
   547  }
   548  
   549  func Arm64ConditionalParamsToAuxInt(v Arm64ConditionalParams) int64 {
   550  	if v.Cond&^0xffff != 0 {
   551  		panic("condition value exceeds 16 bits")
   552  	}
   553  
   554  	var i int64
   555  	if v.Ind {
   556  		i = 1 << 25
   557  	}
   558  	i |= int64(v.ConstVal) << 20
   559  	i |= int64(v.NzcvVal) << 16
   560  	i |= int64(v.Cond)
   561  	return i
   562  }
   563  
   564  type Int64Aux int64
   565  
   566  func (Int64Aux) CanBeAnSSAAux() {}
   567  
   568  func Int64ToAux(v int64) Aux {
   569  	return Int64Aux(v)
   570  }
   571  
   572  // encodes the lsb and width for arm(64) bitfield ops into the expected auxInt format.
   573  func ArmBFAuxInt(lsb, width int64) Arm64BitField {
   574  	if lsb < 0 || lsb > 63 {
   575  		panic("ARM(64) bit field lsb constant out of range")
   576  	}
   577  	if width < 1 || lsb+width > 64 {
   578  		panic("ARM(64) bit field width constant out of range")
   579  	}
   580  	return Arm64BitField(width | lsb<<8)
   581  }
   582  
   583  func AuxIntToArm64BitField(i int64) Arm64BitField {
   584  	return Arm64BitField(i)
   585  }
   586  
   587  func AuxIntToBool(i int64) bool {
   588  	if i == 0 {
   589  		return false
   590  	}
   591  	return true
   592  }
   593  
   594  func AuxIntToFlagConstant(x int64) FlagConstant {
   595  	return FlagConstant(x)
   596  }
   597  
   598  func AuxIntToFloat32(i int64) float32 {
   599  	return float32(math.Float64frombits(uint64(i)))
   600  }
   601  
   602  func AuxIntToFloat64(i int64) float64 {
   603  	return math.Float64frombits(uint64(i))
   604  }
   605  
   606  func AuxIntToInt16(i int64) int16 {
   607  	return int16(i)
   608  }
   609  
   610  func AuxIntToInt32(i int64) int32 {
   611  	return int32(i)
   612  }
   613  
   614  func AuxIntToInt64(i int64) int64 {
   615  	return i
   616  }
   617  
   618  func AuxIntToInt8(i int64) int8 {
   619  	return int8(i)
   620  }
   621  
   622  func AuxIntToOp(cc int64) ssaop.Op {
   623  	return ssaop.Op(cc)
   624  }
   625  
   626  func AuxIntToUint64(i int64) uint64 {
   627  	return uint64(i)
   628  }
   629  
   630  func AuxIntToUint8(i int64) uint8 {
   631  	return uint8(i)
   632  }
   633  
   634  func AuxIntToValAndOff(i int64) ValAndOff {
   635  	return ValAndOff(i)
   636  }
   637  
   638  func AuxToCall(i Aux) *AuxCall {
   639  	return i.(*AuxCall)
   640  }
   641  
   642  func AuxToPanicBoundsC(i Aux) PanicBoundsC {
   643  	return i.(PanicBoundsC)
   644  }
   645  
   646  func AuxToPanicBoundsCC(i Aux) PanicBoundsCC {
   647  	return i.(PanicBoundsCC)
   648  }
   649  
   650  func AuxToS390xCCMask(i Aux) s390x.CCMask {
   651  	return i.(s390x.CCMask)
   652  }
   653  
   654  func AuxToS390xRotateParams(i Aux) s390x.RotateParams {
   655  	return i.(s390x.RotateParams)
   656  }
   657  
   658  func AuxToString(i Aux) string {
   659  	return string(i.(StringAux))
   660  }
   661  
   662  func AuxToSym(i Aux) Sym {
   663  	// TODO: kind of a hack - allows nil interface through
   664  	s, _ := i.(Sym)
   665  	return s
   666  }
   667  
   668  func AuxToType(i Aux) *types.Type {
   669  	return i.(*types.Type)
   670  }
   671  
   672  // B2i translates a boolean value to 0 or 1 for assigning to auxInt.
   673  func B2i(b bool) int64 {
   674  	if b {
   675  		return 1
   676  	}
   677  	return 0
   678  }
   679  
   680  // B2i32 translates a boolean value to 0 or 1.
   681  func B2i32(b bool) int32 {
   682  	if b {
   683  		return 1
   684  	}
   685  	return 0
   686  }
   687  
   688  func CallToAux(s *AuxCall) Aux {
   689  	return s
   690  }
   691  
   692  // CanMergeLoad reports whether the load can be merged into target without
   693  // invalidating the schedule.
   694  func CanMergeLoad(target, load *Value) bool {
   695  	if target.Block.ID != load.Block.ID {
   696  		// If the load is in a different block do not merge it.
   697  		return false
   698  	}
   699  
   700  	// We can't merge the load into the target if the load
   701  	// has more than one use.
   702  	if load.Uses != 1 {
   703  		return false
   704  	}
   705  
   706  	mem := load.MemoryArg()
   707  
   708  	// We need the load's memory arg to still be alive at target. That
   709  	// can't be the case if one of target's args depends on a memory
   710  	// state that is a successor of load's memory arg.
   711  	//
   712  	// For example, it would be invalid to merge load into target in
   713  	// the following situation because newmem has killed oldmem
   714  	// before target is reached:
   715  	//     load = read ... oldmem
   716  	//   newmem = write ... oldmem
   717  	//     arg0 = read ... newmem
   718  	//   target = add arg0 load
   719  	//
   720  	// If the argument comes from a different block then we can exclude
   721  	// it immediately because it must dominate load (which is in the
   722  	// same block as target).
   723  	var args []*Value
   724  	for _, a := range target.Args {
   725  		if a != load && a.Block.ID == target.Block.ID {
   726  			args = append(args, a)
   727  		}
   728  	}
   729  
   730  	f := target.Block.Func
   731  	visited := f.NewSparseSet(f.NumValues())
   732  	defer f.RetSparseSet(visited)
   733  
   734  	// memPreds contains memory states known to be predecessors of load's
   735  	// memory state. It is lazily initialized.
   736  	var memPreds map[*Value]bool
   737  	for len(args) > 0 {
   738  		const limit = 2048 // enough to comfortably cover unrolled crypto blocks
   739  		if visited.Size() >= limit {
   740  			// Give up if we have visited a lot of values.
   741  			return false
   742  		}
   743  		v := args[len(args)-1]
   744  		args = args[:len(args)-1]
   745  		if visited.Contains(v.ID) {
   746  			continue
   747  		}
   748  		visited.Add(v.ID)
   749  		if target.Block.ID != v.Block.ID {
   750  			// Since target and load are in the same block
   751  			// we can stop searching when we leave the block.
   752  			continue
   753  		}
   754  		if v.Op == ssaop.OpPhi {
   755  			// A Phi implies we have reached the top of the block.
   756  			// The memory phi, if it exists, is always
   757  			// the first logical store in the block.
   758  			continue
   759  		}
   760  		if v.Type.IsTuple() && v.Type.FieldType(1).IsMemory() {
   761  			// We could handle this situation however it is likely
   762  			// to be very rare.
   763  			return false
   764  		}
   765  		if v.Op.SymEffect()&ssaop.SymAddr != 0 {
   766  			// This case prevents an operation that calculates the
   767  			// address of a local variable from being forced to schedule
   768  			// before its corresponding VarDef.
   769  			// See issue 28445.
   770  			//   v1 = LOAD ...
   771  			//   v2 = VARDEF
   772  			//   v3 = LEAQ
   773  			//   v4 = CMPQ v1 v3
   774  			// We don't want to combine the CMPQ with the load, because
   775  			// that would force the CMPQ to schedule before the VARDEF, which
   776  			// in turn requires the LEAQ to schedule before the VARDEF.
   777  			return false
   778  		}
   779  		if v.Type.IsMemory() {
   780  			if memPreds == nil {
   781  				// Initialise a map containing memory states
   782  				// known to be predecessors of load's memory
   783  				// state.
   784  				memPreds = make(map[*Value]bool)
   785  				m := mem
   786  				const limit = 50
   787  				for i := 0; i < limit; i++ {
   788  					if m.Op == ssaop.OpPhi {
   789  						// The memory phi, if it exists, is always
   790  						// the first logical store in the block.
   791  						break
   792  					}
   793  					if m.Block.ID != target.Block.ID {
   794  						break
   795  					}
   796  					if !m.Type.IsMemory() {
   797  						break
   798  					}
   799  					memPreds[m] = true
   800  					if len(m.Args) == 0 {
   801  						break
   802  					}
   803  					m = m.MemoryArg()
   804  				}
   805  			}
   806  
   807  			// We can merge if v is a predecessor of mem.
   808  			//
   809  			// For example, we can merge load into target in the
   810  			// following scenario:
   811  			//      x = read ... v
   812  			//    mem = write ... v
   813  			//   load = read ... mem
   814  			// target = add x load
   815  			if memPreds[v] {
   816  				continue
   817  			}
   818  			return false
   819  		}
   820  		if len(v.Args) > 0 && v.Args[len(v.Args)-1] == mem {
   821  			// If v takes mem as an input then we know mem
   822  			// is valid at this point.
   823  			continue
   824  		}
   825  		for _, a := range v.Args {
   826  			if target.Block.ID == a.Block.ID {
   827  				args = append(args, a)
   828  			}
   829  		}
   830  	}
   831  
   832  	return true
   833  }
   834  
   835  // CanMergeLoadClobber reports whether the load can be merged into target without
   836  // invalidating the schedule.
   837  // It also checks that the other non-load argument x is something we
   838  // are ok with clobbering.
   839  func CanMergeLoadClobber(target, load, x *Value) bool {
   840  	// The register containing x is going to get clobbered.
   841  	// Don't merge if we still need the value of x.
   842  	// We don't have liveness information here, but we can
   843  	// approximate x dying with:
   844  	//  1) target is x's only use.
   845  	//  2) target is not in a deeper loop than x.
   846  	switch {
   847  	case x.Uses == 2 && x.Op == ssaop.OpPhi && len(x.Args) == 2 && (x.Args[0] == target || x.Args[1] == target) && target.Uses == 1:
   848  		// This is a simple detector to determine that x is probably
   849  		// not live after target. (It does not need to be perfect,
   850  		// regalloc will issue a reg-reg move to save it if we are wrong.)
   851  		// We have:
   852  		//   x = Phi(?, target)
   853  		//   target = Op(load, x)
   854  		// Because target has only one use as a Phi argument, we can schedule it
   855  		// very late. Hopefully, later than the other use of x. (The other use died
   856  		// between x and target, or exists on another branch entirely).
   857  	case x.Uses > 1:
   858  		return false
   859  	}
   860  	loopnest := x.Block.Func.Loopnest()
   861  	if loopnest.Depth(target.Block.ID) > loopnest.Depth(x.Block.ID) {
   862  		return false
   863  	}
   864  	return CanMergeLoad(target, load)
   865  }
   866  
   867  func CanMergeSym(x, y Sym) bool {
   868  	return x == nil || y == nil
   869  }
   870  
   871  func CanMulStrengthReduce(config *Config, x int64) bool {
   872  	_, ok := config.MulRecipes[x]
   873  	return ok
   874  }
   875  
   876  func CanMulStrengthReduce32(config *Config, x int32) bool {
   877  	_, ok := config.MulRecipes[int64(x)]
   878  	return ok
   879  }
   880  
   881  // CanonLessThan returns whether x is "ordered" less than y, for purposes of normalizing
   882  // generated code as much as possible.
   883  func CanonLessThan(x, y *Value) bool {
   884  	if x.Op != y.Op {
   885  		return x.Op < y.Op
   886  	}
   887  	if !x.Pos.SameFileAndLine(y.Pos) {
   888  		return x.Pos.Before(y.Pos)
   889  	}
   890  	return x.ID < y.ID
   891  }
   892  
   893  // Clobber invalidates values. Returns true.
   894  // Clobber is used by rewrite rules to:
   895  //
   896  //	A) make sure the values are really dead and never used again.
   897  //	B) decrement use counts of the values' args.
   898  func Clobber(vv ...*Value) bool {
   899  	for _, v := range vv {
   900  		v.Reset(ssaop.OpInvalid)
   901  		// Note: leave v.Block intact.  The Block field is used after clobber.
   902  	}
   903  	return true
   904  }
   905  
   906  // ClobberIfDead resets v when use count is 1. Returns true.
   907  // ClobberIfDead is used by rewrite rules to decrement
   908  // use counts of v's args when v is dead and never used.
   909  func ClobberIfDead(v *Value) bool {
   910  	if v.Uses == 1 {
   911  		v.Reset(ssaop.OpInvalid)
   912  	}
   913  	// Note: leave v.Block intact.  The Block field is used after clobberIfDead.
   914  	return true
   915  }
   916  
   917  // CountRule increments Func.ruleMatches[key].
   918  // If Func.ruleMatches is non-nil at the end
   919  // of compilation, it will be printed to stdout.
   920  // This is intended to make it easier to find which functions
   921  // which contain lots of rules matches when developing new rules.
   922  func CountRule(v *Value, key string) bool {
   923  	f := v.Block.Func
   924  	if f.RuleMatches == nil {
   925  		f.RuleMatches = make(map[string]int)
   926  	}
   927  	f.RuleMatches[key]++
   928  	return true
   929  }
   930  
   931  type DeadValueChoice bool
   932  
   933  // Compress mask and shift into single value of the form
   934  // me | mb<<8 | rotate<<16 | nbits<<24 where me and mb can
   935  // be used to regenerate the input mask.
   936  func EncodePPC64RotateMask(rotate, mask, nbits int64) int64 {
   937  	var mb, me, mbn, men int
   938  
   939  	// Determine boundaries and then decode them
   940  	if mask == 0 || ^mask == 0 || rotate >= nbits {
   941  		panic(fmt.Sprintf("invalid PPC64 rotate mask: %x %d %d", uint64(mask), rotate, nbits))
   942  	} else if nbits == 32 {
   943  		mb = bits.LeadingZeros32(uint32(mask))
   944  		me = 32 - bits.TrailingZeros32(uint32(mask))
   945  		mbn = bits.LeadingZeros32(^uint32(mask))
   946  		men = 32 - bits.TrailingZeros32(^uint32(mask))
   947  	} else {
   948  		mb = bits.LeadingZeros64(uint64(mask))
   949  		me = 64 - bits.TrailingZeros64(uint64(mask))
   950  		mbn = bits.LeadingZeros64(^uint64(mask))
   951  		men = 64 - bits.TrailingZeros64(^uint64(mask))
   952  	}
   953  	// Check for a wrapping mask (e.g bits at 0 and 63)
   954  	if mb == 0 && me == int(nbits) {
   955  		// swap the inverted values
   956  		mb, me = men, mbn
   957  	}
   958  
   959  	return int64(me) | int64(mb<<8) | rotate<<16 | nbits<<24
   960  }
   961  
   962  // for a pseudo-op like (LessThan x), extract x.
   963  func FlagArg(v *Value) *Value {
   964  	if len(v.Args) != 1 || !v.Args[0].Type.IsFlags() {
   965  		return nil
   966  	}
   967  	return v.Args[0]
   968  }
   969  
   970  type FlagConstantBuilder struct {
   971  	N bool
   972  	Z bool
   973  	C bool
   974  	V bool
   975  }
   976  
   977  func FlagConstantToAuxInt(x FlagConstant) int64 {
   978  	return int64(x)
   979  }
   980  
   981  func Float32ToAuxInt(f float32) int64 {
   982  	return int64(math.Float64bits(float64(f)))
   983  }
   984  
   985  func Float64ToAuxInt(f float64) int64 {
   986  	return int64(math.Float64bits(f))
   987  }
   988  
   989  // When v is (IMake typ (StructMake ...)), convert to
   990  // (IMake typ arg) where arg is the pointer-y argument to
   991  // the StructMake (there must be exactly one).
   992  func ImakeOfStructMake(v *Value) *Value {
   993  	var arg *Value
   994  	for _, a := range v.Args[1].Args {
   995  		if a.Type.Size() > 0 {
   996  			arg = a
   997  			break
   998  		}
   999  	}
  1000  	return v.Block.NewValue2(v.Pos, ssaop.OpIMake, v.Type, v.Args[0], arg)
  1001  }
  1002  
  1003  func Int16ToAuxInt(i int16) int64 {
  1004  	return int64(i)
  1005  }
  1006  
  1007  func Int32ToAuxInt(i int32) int64 {
  1008  	return int64(i)
  1009  }
  1010  
  1011  func Int64ToAuxInt(i int64) int64 {
  1012  	return i
  1013  }
  1014  
  1015  func Int8ToAuxInt(i int8) int64 {
  1016  	return int64(i)
  1017  }
  1018  
  1019  // Is12Bit reports whether n can be represented as a signed 12 bit integer.
  1020  func Is12Bit(n int64) bool {
  1021  	return -(1<<11) <= n && n < (1<<11)
  1022  }
  1023  
  1024  // IsU12Bit reports whether n can be represented as an unsigned 12 bit integer.
  1025  func IsU12Bit(n int64) bool {
  1026  	return 0 <= n && n < (1<<12)
  1027  }
  1028  
  1029  // Is16Bit reports whether n can be represented as a signed 16 bit integer.
  1030  func Is16Bit(n int64) bool {
  1031  	return n == int64(int16(n))
  1032  }
  1033  
  1034  func Is16BitInt(t *types.Type) bool {
  1035  	return t.Size() == 2 && t.IsInteger()
  1036  }
  1037  
  1038  // Is20Bit reports whether n can be represented as a signed 20 bit integer.
  1039  func Is20Bit(n int64) bool {
  1040  	return -(1<<19) <= n && n < (1<<19)
  1041  }
  1042  
  1043  // Is32Bit reports whether n can be represented as a signed 32 bit integer.
  1044  func Is32Bit(n int64) bool {
  1045  	return n == int64(int32(n))
  1046  }
  1047  
  1048  func Is32BitFloat(t *types.Type) bool {
  1049  	return t.Size() == 4 && t.IsFloat()
  1050  }
  1051  
  1052  func Is32BitInt(t *types.Type) bool {
  1053  	return t.Size() == 4 && t.IsInteger()
  1054  }
  1055  
  1056  // Common functions called from rewriting rules
  1057  
  1058  func Is64BitFloat(t *types.Type) bool {
  1059  	return t.Size() == 8 && t.IsFloat()
  1060  }
  1061  
  1062  func Is64BitInt(t *types.Type) bool {
  1063  	return t.Size() == 8 && t.IsInteger()
  1064  }
  1065  
  1066  func Is8BitInt(t *types.Type) bool {
  1067  	return t.Size() == 1 && t.IsInteger()
  1068  }
  1069  
  1070  // isPowerOfTwoX functions report whether n is a power of 2.
  1071  func IsPowerOfTwo[T int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64](n T) bool {
  1072  	return n > 0 && n&(n-1) == 0
  1073  }
  1074  
  1075  // This verifies that the mask is a set of
  1076  // consecutive bits including the least
  1077  // significant bit.
  1078  func IsPPC64ValidShiftMask(v int64) bool {
  1079  	if (v != 0) && ((v+1)&v) == 0 {
  1080  		return true
  1081  	}
  1082  	return false
  1083  }
  1084  
  1085  // Test if this value can encoded as a mask for a rlwinm like
  1086  // operation.  Masks can also extend from the msb and wrap to
  1087  // the lsb too.  That is, the valid masks are 32 bit strings
  1088  // of the form: 0..01..10..0 or 1..10..01..1 or 1...1
  1089  //
  1090  // Note: This ignores the upper 32 bits of the input. When a
  1091  // zero extended result is desired (e.g a 64 bit result), the
  1092  // user must verify the upper 32 bits are 0 and the mask is
  1093  // contiguous (that is, non-wrapping).
  1094  func IsPPC64WordRotateMask(v64 int64) bool {
  1095  	// Isolate rightmost 1 (if none 0) and add.
  1096  	v := uint32(v64)
  1097  	vp := (v & -v) + v
  1098  	// Likewise, for the wrapping case.
  1099  	vn := ^v
  1100  	vpn := (vn & -vn) + vn
  1101  	return (v&vp == 0 || vn&vpn == 0) && v != 0
  1102  }
  1103  
  1104  func IsPtr(t *types.Type) bool {
  1105  	return t.IsPtrShaped()
  1106  }
  1107  
  1108  // IsSameCall reports whether aux is the same as the given named symbol.
  1109  func IsSameCall(aux Aux, name string) bool {
  1110  	fn := aux.(*AuxCall).Fn
  1111  	return fn != nil && fn.String() == name
  1112  }
  1113  
  1114  // IsU32Bit reports whether n can be represented as an unsigned 32 bit integer.
  1115  func IsU32Bit(n int64) bool {
  1116  	return n == int64(uint32(n))
  1117  }
  1118  
  1119  // IsVolatile reports whether v is a pointer to argument region on stack which
  1120  // will be clobbered by a function call.
  1121  func IsVolatile(v *Value) bool {
  1122  	for v.Op == ssaop.OpOffPtr || v.Op == ssaop.OpAddPtr || v.Op == ssaop.OpPtrIndex || v.Op == ssaop.OpCopy || v.Op == ssaop.OpSelectNAddr {
  1123  		v = v.Args[0]
  1124  	}
  1125  	return v.Op == ssaop.OpSP
  1126  }
  1127  
  1128  const (
  1129  	LeaveDeadValues  DeadValueChoice = false
  1130  	RemoveDeadValues                 = true
  1131  
  1132  	RepZeroThreshold = 1408 // size beyond which we use REP STOS for zeroing
  1133  	RepMoveThreshold = 1408 // size beyond which we use REP MOVS for copying
  1134  )
  1135  
  1136  func Log16(n int16) int64 { return Log16u(uint16(n)) }
  1137  
  1138  func Log16u(n uint16) int64 { return int64(bits.Len16(n)) - 1 }
  1139  
  1140  func Log32(n int32) int64 { return Log32u(uint32(n)) }
  1141  
  1142  func Log32u(n uint32) int64 { return int64(bits.Len32(n)) - 1 }
  1143  
  1144  func Log64(n int64) int64 { return Log64u(uint64(n)) }
  1145  
  1146  func Log64u(n uint64) int64 { return int64(bits.Len64(n)) - 1 }
  1147  
  1148  // logXu returns the logarithm of n base 2.
  1149  // n must be a power of 2 (isPowerOfTwo returns true)
  1150  func Log8u(n uint8) int64 { return int64(bits.Len8(n)) - 1 }
  1151  
  1152  // LogicFlags32 returns flags set to the sign/zeroness of x.
  1153  // C and V are set to false.
  1154  func LogicFlags32(x int32) FlagConstant {
  1155  	var fcb FlagConstantBuilder
  1156  	fcb.Z = x == 0
  1157  	fcb.N = x < 0
  1158  	return fcb.Encode()
  1159  }
  1160  
  1161  // LogicFlags64 returns flags set to the sign/zeroness of x.
  1162  // C and V are set to false.
  1163  func LogicFlags64(x int64) FlagConstant {
  1164  	var fcb FlagConstantBuilder
  1165  	fcb.Z = x == 0
  1166  	fcb.N = x < 0
  1167  	return fcb.Encode()
  1168  }
  1169  
  1170  // LogLargeCopyValue logs the occurrence of a large copy.
  1171  // The best place to do this is in the rewrite rules where the size of the move is easy to find.
  1172  // "Large" is arbitrarily chosen to be 128 bytes; this may change.
  1173  func LogLargeCopyValue(v *Value, s int64) bool {
  1174  	if s < 128 {
  1175  		return true
  1176  	}
  1177  	if logopt.Enabled() {
  1178  		logopt.LogOpt(v.Pos, "copy", "lower", v.Block.Func.Name, fmt.Sprintf("%d bytes", s))
  1179  	}
  1180  	return true
  1181  }
  1182  
  1183  // LogRule logs the use of the rule s. This will only be enabled if
  1184  // rewrite rules were generated with the -log option, see _gen/rulegen.go.
  1185  func LogRule(s string) {
  1186  	if ruleFile == nil {
  1187  		// Open a log file to write log to. We open in append
  1188  		// mode because all.bash runs the compiler lots of times,
  1189  		// and we want the concatenation of all of those logs.
  1190  		// This means, of course, that users need to rm the old log
  1191  		// to get fresh data.
  1192  		// TODO: all.bash runs compilers in parallel. Need to synchronize logging somehow?
  1193  		w, err := os.OpenFile(filepath.Join(os.Getenv("GOROOT"), "src", "rulelog"),
  1194  			os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
  1195  		if err != nil {
  1196  			panic(err)
  1197  		}
  1198  		ruleFile = w
  1199  	}
  1200  	// Ignore errors in case of multiple processes fighting over the file.
  1201  	fmt.Fprintln(ruleFile, s)
  1202  }
  1203  
  1204  func MakeJumpTableSym(b *Block) *obj.LSym {
  1205  	s := base.Ctxt.Lookup(fmt.Sprintf("%s.jump%d", b.Func.Fe.Func().LSym.Name, b.ID))
  1206  	// The jump table symbol is accessed only from the function symbol.
  1207  	s.Set(obj.AttrStatic, true)
  1208  	return s
  1209  }
  1210  
  1211  // Combine (ANDconst [m] (SRWconst [s])) into (RLWINM [y]) or return 0
  1212  func MergePPC64AndSrwi(m, s int64) int64 {
  1213  	mask := MergePPC64RShiftMask(m, s, 32)
  1214  	if !IsPPC64WordRotateMask(mask) {
  1215  		return 0
  1216  	}
  1217  	return EncodePPC64RotateMask((32-s)&31, mask, 32)
  1218  }
  1219  
  1220  // Test if a RLWINM feeding into a CLRLSLDI can be merged into RLWINM.  Return
  1221  // the encoded RLWINM constant, or 0 if they cannot be merged.
  1222  func MergePPC64ClrlsldiRlwinm(sld int32, rlw int64) int64 {
  1223  	r_1, _, _, mask_1 := DecodePPC64RotateMask(rlw)
  1224  	// for CLRLSLDI, it's more convenient to think of it as a mask left bits then rotate left.
  1225  	mask_2 := uint64(0xFFFFFFFFFFFFFFFF) >> uint(GetPPC64Shiftmb(int64(sld)))
  1226  
  1227  	// combine the masks, and adjust for the final left shift.
  1228  	mask_3 := (mask_1 & mask_2) << uint(GetPPC64Shiftsh(int64(sld)))
  1229  	r_2 := GetPPC64Shiftsh(int64(sld))
  1230  	r_3 := (r_1 + r_2) & 31 // This can wrap.
  1231  
  1232  	// Verify the result is still a valid bitmask of <= 32 bits.
  1233  	if !IsPPC64WordRotateMask(int64(mask_3)) || uint64(uint32(mask_3)) != mask_3 {
  1234  		return 0
  1235  	}
  1236  	return EncodePPC64RotateMask(r_3, int64(mask_3), 32)
  1237  }
  1238  
  1239  // Test if a word shift right feeding into a CLRLSLDI can be merged into RLWINM.
  1240  // Return the encoded RLWINM constant, or 0 if they cannot be merged.
  1241  func MergePPC64ClrlsldiSrw(sld, srw int64) int64 {
  1242  	mask_1 := uint64(0xFFFFFFFF >> uint(srw))
  1243  	// for CLRLSLDI, it's more convenient to think of it as a mask left bits then rotate left.
  1244  	mask_2 := uint64(0xFFFFFFFFFFFFFFFF) >> uint(GetPPC64Shiftmb(sld))
  1245  
  1246  	// Rewrite mask to apply after the final left shift.
  1247  	mask_3 := (mask_1 & mask_2) << uint(GetPPC64Shiftsh(sld))
  1248  
  1249  	r_1 := 32 - srw
  1250  	r_2 := GetPPC64Shiftsh(sld)
  1251  	r_3 := (r_1 + r_2) & 31 // This can wrap.
  1252  
  1253  	if uint64(uint32(mask_3)) != mask_3 || mask_3 == 0 {
  1254  		return 0
  1255  	}
  1256  	return EncodePPC64RotateMask(r_3, int64(mask_3), 32)
  1257  }
  1258  
  1259  // Decompose a shift right into an equivalent rotate/mask,
  1260  // and return mask & m.
  1261  func MergePPC64RShiftMask(m, s, nbits int64) int64 {
  1262  	smask := uint64((1<<uint(nbits))-1) >> uint(s)
  1263  	return m & int64(smask)
  1264  }
  1265  
  1266  // Compute the encoded RLWINM constant from combining (SLDconst [sld] (SRWconst [srw] x)),
  1267  // or return 0 if they cannot be combined.
  1268  func MergePPC64SldiSrw(sld, srw int64) int64 {
  1269  	if sld > srw || srw >= 32 {
  1270  		return 0
  1271  	}
  1272  	mask_r := uint32(0xFFFFFFFF) >> uint(srw)
  1273  	mask_l := uint32(0xFFFFFFFF) >> uint(sld)
  1274  	mask := (mask_r & mask_l) << uint(sld)
  1275  	return EncodePPC64RotateMask((32-srw+sld)&31, int64(mask), 32)
  1276  }
  1277  
  1278  // MergeSym merges two symbolic offsets. There is no real merging of
  1279  // offsets, we just pick the non-nil one.
  1280  func MergeSym(x, y Sym) Sym {
  1281  	if x == nil {
  1282  		return y
  1283  	}
  1284  	if y == nil {
  1285  		return x
  1286  	}
  1287  	panic(fmt.Sprintf("mergeSym with two non-nil syms %v %v", x, y))
  1288  }
  1289  
  1290  // MoveSize returns the number of bytes an aligned MOV instruction moves.
  1291  func MoveSize(align int64, c *Config) int64 {
  1292  	switch {
  1293  	case align%8 == 0 && c.PtrSize == 8:
  1294  		return 8
  1295  	case align%4 == 0:
  1296  		return 4
  1297  	case align%2 == 0:
  1298  		return 2
  1299  	}
  1300  	return 1
  1301  }
  1302  
  1303  // MulStrengthReduce returns v*x evaluated at the location
  1304  // (block and source position) of m.
  1305  // canMulStrengthReduce must have returned true.
  1306  func MulStrengthReduce(m *Value, v *Value, x int64) *Value {
  1307  	return v.Block.Func.Config.MulRecipes[x].Build(m, v)
  1308  }
  1309  
  1310  // MulStrengthReduce32 returns v*x evaluated at the location
  1311  // (block and source position) of m.
  1312  // canMulStrengthReduce32 must have returned true.
  1313  // The upper 32 bits of m might be set to junk.
  1314  func MulStrengthReduce32(m *Value, v *Value, x int32) *Value {
  1315  	return v.Block.Func.Config.MulRecipes[int64(x)].Build(m, v)
  1316  }
  1317  
  1318  func NewPPC64ShiftAuxInt(sh, mb, me, sz int64) int32 {
  1319  	if sh < 0 || sh >= sz {
  1320  		panic("PPC64 shift arg sh out of range")
  1321  	}
  1322  	if mb < 0 || mb >= sz {
  1323  		panic("PPC64 shift arg mb out of range")
  1324  	}
  1325  	if me < 0 || me >= sz {
  1326  		panic("PPC64 shift arg me out of range")
  1327  	}
  1328  	return int32(sh<<16 | mb<<8 | me)
  1329  }
  1330  
  1331  // NoteRule is an easy way to track if a rule is matched when writing
  1332  // new ones.  Make the rule of interest also conditional on
  1333  //
  1334  //	NoteRule("note to self: rule of interest matched")
  1335  //
  1336  // and that message will print when the rule matches.
  1337  func NoteRule(s string) bool {
  1338  	fmt.Println(s)
  1339  	return true
  1340  }
  1341  
  1342  // ntzX returns the number of trailing zeros.
  1343  func Ntz64(x int64) int { return bits.TrailingZeros64(uint64(x)) }
  1344  
  1345  // OneBit reports whether x contains exactly one set bit.
  1346  func OneBit[T int8 | int16 | int32 | int64](x T) bool {
  1347  	return x&(x-1) == 0 && x != 0
  1348  }
  1349  
  1350  func OpToAuxInt(o ssaop.Op) int64 {
  1351  	return int64(o)
  1352  }
  1353  
  1354  func PanicBoundsCCToAux(p PanicBoundsCC) Aux {
  1355  	return p
  1356  }
  1357  
  1358  func PanicBoundsCToAux(p PanicBoundsC) Aux {
  1359  	return p
  1360  }
  1361  
  1362  // Read16 reads two bytes from the read-only global sym at offset off.
  1363  func Read16(sym Sym, off int64, byteorder binary.ByteOrder) uint16 {
  1364  	lsym := sym.(*obj.LSym)
  1365  	// lsym.P is written lazily.
  1366  	// Bytes requested after the end of lsym.P are 0.
  1367  	var src []byte
  1368  	if 0 <= off && off < int64(len(lsym.P)) {
  1369  		src = lsym.P[off:]
  1370  	}
  1371  	buf := make([]byte, 2)
  1372  	copy(buf, src)
  1373  	return byteorder.Uint16(buf)
  1374  }
  1375  
  1376  // Read32 reads four bytes from the read-only global sym at offset off.
  1377  func Read32(sym Sym, off int64, byteorder binary.ByteOrder) uint32 {
  1378  	lsym := sym.(*obj.LSym)
  1379  	var src []byte
  1380  	if 0 <= off && off < int64(len(lsym.P)) {
  1381  		src = lsym.P[off:]
  1382  	}
  1383  	buf := make([]byte, 4)
  1384  	copy(buf, src)
  1385  	return byteorder.Uint32(buf)
  1386  }
  1387  
  1388  // Read64 reads eight bytes from the read-only global sym at offset off.
  1389  func Read64(sym Sym, off int64, byteorder binary.ByteOrder) uint64 {
  1390  	lsym := sym.(*obj.LSym)
  1391  	var src []byte
  1392  	if 0 <= off && off < int64(len(lsym.P)) {
  1393  		src = lsym.P[off:]
  1394  	}
  1395  	buf := make([]byte, 8)
  1396  	copy(buf, src)
  1397  	return byteorder.Uint64(buf)
  1398  }
  1399  
  1400  // Read8 reads one byte from the read-only global sym at offset off.
  1401  func Read8(sym Sym, off int64) uint8 {
  1402  	lsym := sym.(*obj.LSym)
  1403  	if off >= int64(len(lsym.P)) || off < 0 {
  1404  		// Invalid index into the global sym.
  1405  		// This can happen in dead code, so we don't want to panic.
  1406  		// Just return any value, it will eventually get ignored.
  1407  		// See issue 29215.
  1408  		return 0
  1409  	}
  1410  	return lsym.P[off]
  1411  }
  1412  
  1413  func RewriteStructStore(v *Value) *Value {
  1414  	b := v.Block
  1415  	dst := v.Args[0]
  1416  	x := v.Args[1]
  1417  	if x.Op != ssaop.OpStructMake {
  1418  		base.Fatalf("invalid struct store: %v", x)
  1419  	}
  1420  	mem := v.Args[2]
  1421  
  1422  	t := x.Type
  1423  	for i, arg := range x.Args {
  1424  		ft := t.FieldType(i)
  1425  
  1426  		addr := b.NewValue1I(v.Pos, ssaop.OpOffPtr, ft.PtrTo(), t.FieldOff(i), dst)
  1427  		mem = b.NewValue3A(v.Pos, ssaop.OpStore, types.TypeMem, TypeToAux(ft), addr, arg, mem)
  1428  	}
  1429  
  1430  	return mem
  1431  }
  1432  
  1433  func S390xCCMaskToAux(c s390x.CCMask) Aux {
  1434  	return c
  1435  }
  1436  
  1437  func S390xRotateParamsToAux(r s390x.RotateParams) Aux {
  1438  	return r
  1439  }
  1440  
  1441  // SetPos sets the position of v to pos, then returns true.
  1442  // Useful for setting the result of a rewrite's position to
  1443  // something other than the default.
  1444  func SetPos(v *Value, pos src.XPos) bool {
  1445  	v.Pos = pos
  1446  	return true
  1447  }
  1448  
  1449  // ShiftIsBounded reports whether (left/right) shift Value v is known to be bounded.
  1450  // A shift is bounded if it is shifting by less than the width of the shifted value.
  1451  func ShiftIsBounded(v *Value) bool {
  1452  	return v.AuxInt != 0
  1453  }
  1454  
  1455  // SubFlags32 returns the flags that would be set from computing x-y.
  1456  func SubFlags32(x, y int32) FlagConstant {
  1457  	var fcb FlagConstantBuilder
  1458  	fcb.Z = x-y == 0
  1459  	fcb.N = x-y < 0
  1460  	fcb.C = uint32(y) <= uint32(x) // This code follows the arm carry flag model.
  1461  	fcb.V = x >= 0 && y < 0 && x-y < 0 || x < 0 && y >= 0 && x-y >= 0
  1462  	return fcb.Encode()
  1463  }
  1464  
  1465  // SubFlags64 returns the flags that would be set from computing x-y.
  1466  func SubFlags64(x, y int64) FlagConstant {
  1467  	var fcb FlagConstantBuilder
  1468  	fcb.Z = x-y == 0
  1469  	fcb.N = x-y < 0
  1470  	fcb.C = uint64(y) <= uint64(x) // This code follows the arm carry flag model.
  1471  	fcb.V = x >= 0 && y < 0 && x-y < 0 || x < 0 && y >= 0 && x-y >= 0
  1472  	return fcb.Encode()
  1473  }
  1474  
  1475  func SupportsPPC64PCRel() bool {
  1476  	// PCRel is currently supported for >= power10, linux only
  1477  	// Internal and external linking supports this on ppc64le; internal linking on ppc64.
  1478  	return buildcfg.GOPPC64 >= 10 && buildcfg.GOOS == "linux"
  1479  }
  1480  
  1481  // SymIsRO reports whether sym is a read-only global.
  1482  func SymIsRO(sym Sym) bool {
  1483  	lsym := sym.(*obj.LSym)
  1484  	return lsym.Type == objabi.SRODATA && len(lsym.R) == 0
  1485  }
  1486  
  1487  func SymToAux(s Sym) Aux {
  1488  	return s
  1489  }
  1490  
  1491  func TypeToAux(t *types.Type) Aux {
  1492  	return t
  1493  }
  1494  
  1495  func Uint64ToAuxInt(i uint64) int64 {
  1496  	return int64(i)
  1497  }
  1498  
  1499  func Uint8ToAuxInt(i uint8) int64 {
  1500  	return int64(int8(i))
  1501  }
  1502  
  1503  func ValAndOffToAuxInt(v ValAndOff) int64 {
  1504  	return int64(v)
  1505  }
  1506  
  1507  var ruleFile io.Writer
  1508  
  1509  func (fcs FlagConstantBuilder) Encode() FlagConstant {
  1510  	var fc FlagConstant
  1511  	if fcs.N {
  1512  		fc |= 1
  1513  	}
  1514  	if fcs.Z {
  1515  		fc |= 2
  1516  	}
  1517  	if fcs.C {
  1518  		fc |= 4
  1519  	}
  1520  	if fcs.V {
  1521  		fc |= 8
  1522  	}
  1523  	return fc
  1524  }
  1525  
  1526  func IsConstZero(v *Value) bool {
  1527  	switch v.Op {
  1528  	case ssaop.OpConstNil:
  1529  		return true
  1530  	case ssaop.OpConst64, ssaop.OpConst32, ssaop.OpConst16, ssaop.OpConst8, ssaop.OpConstBool, ssaop.OpConst32F, ssaop.OpConst64F:
  1531  		return v.AuxInt == 0
  1532  	case ssaop.OpStringMake, ssaop.OpIMake, ssaop.OpComplexMake:
  1533  		return IsConstZero(v.Args[0]) && IsConstZero(v.Args[1])
  1534  	case ssaop.OpSliceMake:
  1535  		return IsConstZero(v.Args[0]) && IsConstZero(v.Args[1]) && IsConstZero(v.Args[2])
  1536  	case ssaop.OpStringPtr, ssaop.OpStringLen, ssaop.OpSlicePtr, ssaop.OpSliceLen, ssaop.OpSliceCap, ssaop.OpITab, ssaop.OpIData, ssaop.OpComplexReal, ssaop.OpComplexImag:
  1537  		return IsConstZero(v.Args[0])
  1538  	}
  1539  	return false
  1540  }
  1541  
  1542  // getContiguousOnesBounds returns the bit positions (msb, lsb) of the contiguous
  1543  // ones in n within its bit width, using standard hardware bit numbering (LSB = 0,
  1544  // MSB = bitWidth - 1). Returns (-1, -1) if the ones are not contiguous.
  1545  func getContiguousOnesBounds[T uint16 | uint32 | uint64](n T) (msb, lsb int) {
  1546  	if n == 0 || n == ^T(0) {
  1547  		return -1, -1
  1548  	}
  1549  
  1550  	v := uint64(n)
  1551  	msb = 63 - bits.LeadingZeros64(v)
  1552  	lsb = bits.TrailingZeros64(v)
  1553  	if (msb - lsb + 1) != bits.OnesCount64(v) {
  1554  		return -1, -1
  1555  	}
  1556  
  1557  	return msb, lsb
  1558  }
  1559  
  1560  // getContiguousZerosBounds returns the bit positions (msb, lsb) of the contiguous
  1561  // zeros in n within its bit width, using standard hardware bit numbering (LSB = 0,
  1562  // MSB = bitWidth - 1). Returns (-1, -1) if the zeros are not contiguous.
  1563  func getContiguousZerosBounds[T uint16 | uint32 | uint64](n T) (msb, lsb int) {
  1564  	return getContiguousOnesBounds(^n)
  1565  }
  1566  
  1567  // IsContiguousZeros reports whether all zero bits in n form a single
  1568  // contiguous block within its bit width:
  1569  //
  1570  //	  valid: 00..11, 11..00, or 11..00..11
  1571  //	rejects: 00..11..00 or multiple 0-blocks
  1572  func IsContiguousZeros[T uint16 | uint32 | uint64](n T) bool {
  1573  	msb, lsb := getContiguousZerosBounds(n)
  1574  	return msb != -1 && lsb != -1
  1575  }
  1576  
  1577  // IsContiguousOnes reports whether all one bits in n form a single
  1578  // contiguous block within its bit width:
  1579  //
  1580  //	  valid: 11..00, 00..11, or 00..11..00
  1581  //	rejects: 11..00..11 or multiple 1-blocks
  1582  func IsContiguousOnes[T uint16 | uint32 | uint64](n T) bool {
  1583  	msb, lsb := getContiguousOnesBounds(n)
  1584  	return msb != -1 && lsb != -1
  1585  }
  1586  
  1587  // GetContiguousOnesLSB returns the least significant bit position of the
  1588  // single contiguous one region in n. It panics if n does not contain a
  1589  // unique contiguous one region.
  1590  func GetContiguousOnesLSB[T uint16 | uint32 | uint64](n T) int64 {
  1591  	msb, lsb := getContiguousOnesBounds(n)
  1592  	if msb == -1 || lsb == -1 {
  1593  		panic(fmt.Sprintf("LOONG64: invalid immediate 0x%016x, no unique contiguous one region", n))
  1594  	}
  1595  
  1596  	return int64(lsb)
  1597  }
  1598  
  1599  // GetLoong64BSTRINSVAuxInt encodes the bit-field boundaries (msbd, lsbd) of the
  1600  // contiguous zero region in a 64-bit mask n into the auxInt format required by
  1601  // the LoongArch64 BSTRINSV instruction (msbd = auxInt>>6, lsbd = auxInt&0x3f).
  1602  // It panics if n does not contain a unique contiguous zero region.
  1603  func GetLoong64BSTRINSVAuxInt(n uint64) int64 {
  1604  	msb, lsb := getContiguousZerosBounds(n)
  1605  	if msb == -1 || lsb == -1 {
  1606  		panic(fmt.Sprintf("LOONG64: invalid immediate 0x%016x, no unique contiguous zero region", n))
  1607  	}
  1608  
  1609  	return int64((msb << 6) | lsb)
  1610  }
  1611  
  1612  // GetLoong64BSTRPICKVAuxInt encodes the bit-field boundaries (msbd, lsbd) of the
  1613  // contiguous one region in a 64-bit mask n into the auxInt format required by
  1614  // the LoongArch64 BSTRPICKV operation (msbd = auxInt>>6, lsbd = auxInt&0x3f).
  1615  // It panics if n does not contain a unique contiguous one region.
  1616  func GetLoong64BSTRPICKVAuxInt(n uint64) int64 {
  1617  	msb, lsb := getContiguousOnesBounds(n)
  1618  	if msb == -1 || lsb == -1 {
  1619  		panic(fmt.Sprintf("LOONG64: invalid immediate 0x%016x, no unique contiguous one region", n))
  1620  	}
  1621  
  1622  	return int64((msb << 6) | lsb)
  1623  }
  1624  

View as plain text