Source file src/cmd/compile/internal/walk/range.go

     1  // Copyright 2009 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 walk
     6  
     7  import (
     8  	"internal/buildcfg"
     9  	"unicode/utf8"
    10  
    11  	"cmd/compile/internal/base"
    12  	"cmd/compile/internal/ir"
    13  	"cmd/compile/internal/reflectdata"
    14  	"cmd/compile/internal/ssagen"
    15  	"cmd/compile/internal/typecheck"
    16  	"cmd/compile/internal/types"
    17  	"cmd/internal/src"
    18  	"cmd/internal/sys"
    19  )
    20  
    21  func cheapComputableIndex(width int64) bool {
    22  	switch ssagen.Arch.LinkArch.Family {
    23  	// MIPS does not have R+R addressing
    24  	// Arm64 may lack ability to generate this code in our assembler,
    25  	// but the architecture supports it.
    26  	case sys.PPC64, sys.S390X:
    27  		return width == 1
    28  	case sys.AMD64, sys.I386, sys.ARM64, sys.ARM:
    29  		switch width {
    30  		case 1, 2, 4, 8:
    31  			return true
    32  		}
    33  	}
    34  	return false
    35  }
    36  
    37  // walkRange transforms various forms of ORANGE into
    38  // simpler forms.  The result must be assigned back to n.
    39  // Node n may also be modified in place, and may also be
    40  // the returned node.
    41  func walkRange(nrange *ir.RangeStmt) ir.Node {
    42  	base.Assert(!nrange.DistinctVars) // Should all be rewritten before escape analysis
    43  	if isMapClear(nrange) {
    44  		return mapRangeClear(nrange)
    45  	}
    46  
    47  	nfor := ir.NewForStmt(nrange.Pos(), nil, nil, nil, nil, nrange.DistinctVars)
    48  	nfor.SetInit(nrange.Init())
    49  	nfor.Label = nrange.Label
    50  
    51  	// variable name conventions:
    52  	//	ohv1, hv1, hv2: hidden (old) val 1, 2
    53  	//	ha, hit: hidden aggregate, iterator
    54  	//	hn, hp: hidden len, pointer
    55  	//	hb: hidden bool
    56  	//	a, v1, v2: not hidden aggregate, val 1, 2
    57  
    58  	a := nrange.X
    59  	t := a.Type()
    60  	lno := ir.SetPos(a)
    61  
    62  	v1, v2 := nrange.Key, nrange.Value
    63  
    64  	if ir.IsBlank(v2) {
    65  		v2 = nil
    66  	}
    67  
    68  	if ir.IsBlank(v1) && v2 == nil {
    69  		v1 = nil
    70  	}
    71  
    72  	if v1 == nil && v2 != nil {
    73  		base.Fatalf("walkRange: v2 != nil while v1 == nil")
    74  	}
    75  
    76  	var body []ir.Node
    77  	var init []ir.Node
    78  	switch k := t.Kind(); {
    79  	default:
    80  		base.Fatalf("walkRange")
    81  
    82  	case types.IsInt[k]:
    83  		hv1 := typecheck.TempAt(base.Pos, ir.CurFunc, t)
    84  		hn := typecheck.TempAt(base.Pos, ir.CurFunc, t)
    85  
    86  		init = append(init, ir.NewAssignStmt(base.Pos, hv1, nil))
    87  		init = append(init, ir.NewAssignStmt(base.Pos, hn, a))
    88  
    89  		nfor.Cond = ir.NewBinaryExpr(base.Pos, ir.OLT, hv1, hn)
    90  		nfor.Post = ir.NewAssignStmt(base.Pos, hv1, ir.NewBinaryExpr(base.Pos, ir.OADD, hv1, ir.NewInt(base.Pos, 1)))
    91  
    92  		if v1 != nil {
    93  			body = []ir.Node{rangeAssign(nrange, hv1)}
    94  		}
    95  
    96  	case k == types.TARRAY, k == types.TSLICE, k == types.TPTR: // TPTR is pointer-to-array
    97  		if nn := arrayRangeClear(nrange, v1, v2, a); nn != nil {
    98  			base.Pos = lno
    99  			return nn
   100  		}
   101  
   102  		// Element type of the iteration
   103  		var elem *types.Type
   104  		switch t.Kind() {
   105  		case types.TSLICE, types.TARRAY:
   106  			elem = t.Elem()
   107  		case types.TPTR:
   108  			elem = t.Elem().Elem()
   109  		}
   110  
   111  		// order.stmt arranged for a copy of the array/slice variable if needed.
   112  		ha := a
   113  
   114  		hv1 := typecheck.TempAt(base.Pos, ir.CurFunc, types.Types[types.TINT])
   115  		hn := typecheck.TempAt(base.Pos, ir.CurFunc, types.Types[types.TINT])
   116  
   117  		init = append(init, ir.NewAssignStmt(base.Pos, hv1, nil))
   118  		init = append(init, ir.NewAssignStmt(base.Pos, hn, ir.NewUnaryExpr(base.Pos, ir.OLEN, ha)))
   119  
   120  		nfor.Cond = ir.NewBinaryExpr(base.Pos, ir.OLT, hv1, hn)
   121  		nfor.Post = ir.NewAssignStmt(base.Pos, hv1, ir.NewBinaryExpr(base.Pos, ir.OADD, hv1, ir.NewInt(base.Pos, 1)))
   122  
   123  		// for range ha { body }
   124  		if v1 == nil {
   125  			break
   126  		}
   127  
   128  		// for v1 := range ha { body }
   129  		if v2 == nil {
   130  			body = []ir.Node{rangeAssign(nrange, hv1)}
   131  			break
   132  		}
   133  
   134  		// for v1, v2 := range ha { body }
   135  		if cheapComputableIndex(elem.Size()) {
   136  			// v1, v2 = hv1, ha[hv1]
   137  			tmp := ir.NewIndexExpr(base.Pos, ha, hv1)
   138  			tmp.SetBounded(true)
   139  			body = []ir.Node{rangeAssign2(nrange, hv1, tmp)}
   140  			break
   141  		}
   142  
   143  		// Slice to iterate over
   144  		var hs ir.Node
   145  		if t.IsSlice() {
   146  			hs = ha
   147  		} else {
   148  			var arr ir.Node
   149  			if t.IsPtr() {
   150  				arr = ha
   151  			} else {
   152  				arr = typecheck.NodAddr(ha)
   153  				arr.SetType(t.PtrTo())
   154  				arr.SetTypecheck(1)
   155  			}
   156  			hs = ir.NewSliceExpr(base.Pos, ir.OSLICEARR, arr, nil, nil, nil)
   157  			// old typechecker doesn't know OSLICEARR, so we set types explicitly
   158  			hs.SetType(types.NewSlice(elem))
   159  			hs.SetTypecheck(1)
   160  		}
   161  
   162  		// We use a "pointer" to keep track of where we are in the backing array
   163  		// of the slice hs. This pointer starts at hs.ptr and gets incremented
   164  		// by the element size each time through the loop.
   165  		//
   166  		// It's tricky, though, as on the last iteration this pointer gets
   167  		// incremented to point past the end of the backing array. We can't
   168  		// let the garbage collector see that final out-of-bounds pointer.
   169  		//
   170  		// To avoid this, we keep the "pointer" alternately in 2 variables, one
   171  		// pointer typed and one uintptr typed. Most of the time it lives in the
   172  		// regular pointer variable, but when it might be out of bounds (after it
   173  		// has been incremented, but before the loop condition has been checked)
   174  		// it lives briefly in the uintptr variable.
   175  		//
   176  		// hp contains the pointer version (of type *T, where T is the element type).
   177  		// It is guaranteed to always be in range, keeps the backing store alive,
   178  		// and is updated on stack copies. If a GC occurs when this function is
   179  		// suspended at any safepoint, this variable ensures correct operation.
   180  		//
   181  		// hu contains the equivalent uintptr version. It may point past the
   182  		// end, but doesn't keep the backing store alive and doesn't get updated
   183  		// on a stack copy. If a GC occurs while this function is on the top of
   184  		// the stack, then the last frame is scanned conservatively and hu will
   185  		// act as a reference to the backing array to ensure it is not collected.
   186  		//
   187  		// The "pointer" we're moving across the backing array lives in one
   188  		// or the other of hp and hu as the loop proceeds.
   189  		//
   190  		// hp is live during most of the body of the loop. But it isn't live
   191  		// at the very top of the loop, when we haven't checked i<n yet, and
   192  		// it could point off the end of the backing store.
   193  		// hu is live only at the very top and very bottom of the loop.
   194  		// In particular, only when it cannot possibly be live across a call.
   195  		//
   196  		// So we do
   197  		//   hu = uintptr(unsafe.Pointer(hs.ptr))
   198  		//   for i := 0; i < hs.len; i++ {
   199  		//     hp = (*T)(unsafe.Pointer(hu))
   200  		//     v1, v2 = i, *hp
   201  		//     ... body of loop ...
   202  		//     hu = uintptr(unsafe.Pointer(hp)) + elemsize
   203  		//   }
   204  		//
   205  		// Between the assignments to hu and the assignment back to hp, there
   206  		// must not be any calls.
   207  
   208  		// Pointer to current iteration position. Start on entry to the loop
   209  		// with the pointer in hu.
   210  		ptr := ir.NewUnaryExpr(base.Pos, ir.OSPTR, hs)
   211  		ptr.SetBounded(true)
   212  		huVal := ir.NewConvExpr(base.Pos, ir.OCONVNOP, types.Types[types.TUNSAFEPTR], ptr)
   213  		huVal = ir.NewConvExpr(base.Pos, ir.OCONVNOP, types.Types[types.TUINTPTR], huVal)
   214  		hu := typecheck.TempAt(base.Pos, ir.CurFunc, types.Types[types.TUINTPTR])
   215  		init = append(init, ir.NewAssignStmt(base.Pos, hu, huVal))
   216  
   217  		// Convert hu to hp at the top of the loop (after the condition has been checked).
   218  		hpVal := ir.NewConvExpr(base.Pos, ir.OCONVNOP, types.Types[types.TUNSAFEPTR], hu)
   219  		hpVal.SetCheckPtr(true) // disable checkptr on this conversion
   220  		hpVal = ir.NewConvExpr(base.Pos, ir.OCONVNOP, elem.PtrTo(), hpVal)
   221  		hp := typecheck.TempAt(base.Pos, ir.CurFunc, elem.PtrTo())
   222  		body = append(body, ir.NewAssignStmt(base.Pos, hp, hpVal))
   223  
   224  		// Assign variables on the LHS of the range statement. Use *hp to get the element.
   225  		e := ir.NewStarExpr(base.Pos, hp)
   226  		e.SetBounded(true)
   227  		a := rangeAssign2(nrange, hv1, e)
   228  		body = append(body, a)
   229  
   230  		// Advance pointer for next iteration of the loop.
   231  		// This reads from hp and writes to hu.
   232  		huVal = ir.NewConvExpr(base.Pos, ir.OCONVNOP, types.Types[types.TUNSAFEPTR], hp)
   233  		huVal = ir.NewConvExpr(base.Pos, ir.OCONVNOP, types.Types[types.TUINTPTR], huVal)
   234  		as := ir.NewAssignStmt(base.Pos, hu, ir.NewBinaryExpr(base.Pos, ir.OADD, huVal, ir.NewInt(base.Pos, elem.Size())))
   235  		nfor.Post = ir.NewBlockStmt(base.Pos, []ir.Node{nfor.Post, as})
   236  
   237  	case k == types.TMAP:
   238  		// order.stmt allocated the iterator for us.
   239  		// we only use a once, so no copy needed.
   240  		ha := a
   241  
   242  		hit := nrange.Prealloc
   243  		th := hit.Type()
   244  		// depends on layout of iterator struct.
   245  		// See cmd/compile/internal/reflectdata/reflect.go:MapIterType
   246  		var keysym, elemsym *types.Sym
   247  		if buildcfg.Experiment.SwissMap {
   248  			keysym = th.Field(0).Sym
   249  			elemsym = th.Field(1).Sym // ditto
   250  		} else {
   251  			keysym = th.Field(0).Sym
   252  			elemsym = th.Field(1).Sym // ditto
   253  		}
   254  
   255  		fn := typecheck.LookupRuntime("mapiterinit", t.Key(), t.Elem(), th)
   256  		init = append(init, mkcallstmt1(fn, reflectdata.RangeMapRType(base.Pos, nrange), ha, typecheck.NodAddr(hit)))
   257  		nfor.Cond = ir.NewBinaryExpr(base.Pos, ir.ONE, ir.NewSelectorExpr(base.Pos, ir.ODOT, hit, keysym), typecheck.NodNil())
   258  
   259  		fn = typecheck.LookupRuntime("mapiternext", th)
   260  		nfor.Post = mkcallstmt1(fn, typecheck.NodAddr(hit))
   261  
   262  		key := ir.NewStarExpr(base.Pos, typecheck.ConvNop(ir.NewSelectorExpr(base.Pos, ir.ODOT, hit, keysym), types.NewPtr(t.Key())))
   263  		if v1 == nil {
   264  			body = nil
   265  		} else if v2 == nil {
   266  			body = []ir.Node{rangeAssign(nrange, key)}
   267  		} else {
   268  			elem := ir.NewStarExpr(base.Pos, typecheck.ConvNop(ir.NewSelectorExpr(base.Pos, ir.ODOT, hit, elemsym), types.NewPtr(t.Elem())))
   269  			body = []ir.Node{rangeAssign2(nrange, key, elem)}
   270  		}
   271  
   272  	case k == types.TCHAN:
   273  		// order.stmt arranged for a copy of the channel variable.
   274  		ha := a
   275  
   276  		hv1 := typecheck.TempAt(base.Pos, ir.CurFunc, t.Elem())
   277  		hv1.SetTypecheck(1)
   278  		if t.Elem().HasPointers() {
   279  			init = append(init, ir.NewAssignStmt(base.Pos, hv1, nil))
   280  		}
   281  		hb := typecheck.TempAt(base.Pos, ir.CurFunc, types.Types[types.TBOOL])
   282  
   283  		nfor.Cond = ir.NewBinaryExpr(base.Pos, ir.ONE, hb, ir.NewBool(base.Pos, false))
   284  		lhs := []ir.Node{hv1, hb}
   285  		rhs := []ir.Node{ir.NewUnaryExpr(base.Pos, ir.ORECV, ha)}
   286  		a := ir.NewAssignListStmt(base.Pos, ir.OAS2RECV, lhs, rhs)
   287  		a.SetTypecheck(1)
   288  		nfor.Cond = ir.InitExpr([]ir.Node{a}, nfor.Cond)
   289  		if v1 == nil {
   290  			body = nil
   291  		} else {
   292  			body = []ir.Node{rangeAssign(nrange, hv1)}
   293  		}
   294  		// Zero hv1. This prevents hv1 from being the sole, inaccessible
   295  		// reference to an otherwise GC-able value during the next channel receive.
   296  		// See issue 15281.
   297  		body = append(body, ir.NewAssignStmt(base.Pos, hv1, nil))
   298  
   299  	case k == types.TSTRING:
   300  		// Transform string range statements like "for v1, v2 = range a" into
   301  		//
   302  		// ha := a
   303  		// for hv1 := 0; hv1 < len(ha); {
   304  		//   hv1t := hv1
   305  		//   hv2 := rune(ha[hv1])
   306  		//   if hv2 < utf8.RuneSelf {
   307  		//      hv1++
   308  		//   } else {
   309  		//      hv2, hv1 = decoderune(ha, hv1)
   310  		//   }
   311  		//   v1, v2 = hv1t, hv2
   312  		//   // original body
   313  		// }
   314  
   315  		// order.stmt arranged for a copy of the string variable.
   316  		ha := a
   317  
   318  		hv1 := typecheck.TempAt(base.Pos, ir.CurFunc, types.Types[types.TINT])
   319  		hv1t := typecheck.TempAt(base.Pos, ir.CurFunc, types.Types[types.TINT])
   320  		hv2 := typecheck.TempAt(base.Pos, ir.CurFunc, types.RuneType)
   321  
   322  		// hv1 := 0
   323  		init = append(init, ir.NewAssignStmt(base.Pos, hv1, nil))
   324  
   325  		// hv1 < len(ha)
   326  		nfor.Cond = ir.NewBinaryExpr(base.Pos, ir.OLT, hv1, ir.NewUnaryExpr(base.Pos, ir.OLEN, ha))
   327  
   328  		if v1 != nil {
   329  			// hv1t = hv1
   330  			body = append(body, ir.NewAssignStmt(base.Pos, hv1t, hv1))
   331  		}
   332  
   333  		// hv2 := rune(ha[hv1])
   334  		nind := ir.NewIndexExpr(base.Pos, ha, hv1)
   335  		nind.SetBounded(true)
   336  		body = append(body, ir.NewAssignStmt(base.Pos, hv2, typecheck.Conv(nind, types.RuneType)))
   337  
   338  		// if hv2 < utf8.RuneSelf
   339  		nif := ir.NewIfStmt(base.Pos, nil, nil, nil)
   340  		nif.Cond = ir.NewBinaryExpr(base.Pos, ir.OLT, hv2, ir.NewInt(base.Pos, utf8.RuneSelf))
   341  
   342  		// hv1++
   343  		nif.Body = []ir.Node{ir.NewAssignStmt(base.Pos, hv1, ir.NewBinaryExpr(base.Pos, ir.OADD, hv1, ir.NewInt(base.Pos, 1)))}
   344  
   345  		// } else {
   346  		// hv2, hv1 = decoderune(ha, hv1)
   347  		fn := typecheck.LookupRuntime("decoderune")
   348  		call := mkcall1(fn, fn.Type().ResultsTuple(), &nif.Else, ha, hv1)
   349  		a := ir.NewAssignListStmt(base.Pos, ir.OAS2, []ir.Node{hv2, hv1}, []ir.Node{call})
   350  		nif.Else.Append(a)
   351  
   352  		body = append(body, nif)
   353  
   354  		if v1 != nil {
   355  			if v2 != nil {
   356  				// v1, v2 = hv1t, hv2
   357  				body = append(body, rangeAssign2(nrange, hv1t, hv2))
   358  			} else {
   359  				// v1 = hv1t
   360  				body = append(body, rangeAssign(nrange, hv1t))
   361  			}
   362  		}
   363  	}
   364  
   365  	typecheck.Stmts(init)
   366  
   367  	nfor.PtrInit().Append(init...)
   368  
   369  	typecheck.Stmts(nfor.Cond.Init())
   370  
   371  	nfor.Cond = typecheck.Expr(nfor.Cond)
   372  	nfor.Cond = typecheck.DefaultLit(nfor.Cond, nil)
   373  	nfor.Post = typecheck.Stmt(nfor.Post)
   374  	typecheck.Stmts(body)
   375  	nfor.Body.Append(body...)
   376  	nfor.Body.Append(nrange.Body...)
   377  
   378  	var n ir.Node = nfor
   379  
   380  	n = walkStmt(n)
   381  
   382  	base.Pos = lno
   383  	return n
   384  }
   385  
   386  // rangeAssign returns "n.Key = key".
   387  func rangeAssign(n *ir.RangeStmt, key ir.Node) ir.Node {
   388  	key = rangeConvert(n, n.Key.Type(), key, n.KeyTypeWord, n.KeySrcRType)
   389  	return ir.NewAssignStmt(n.Pos(), n.Key, key)
   390  }
   391  
   392  // rangeAssign2 returns "n.Key, n.Value = key, value".
   393  func rangeAssign2(n *ir.RangeStmt, key, value ir.Node) ir.Node {
   394  	// Use OAS2 to correctly handle assignments
   395  	// of the form "v1, a[v1] = range".
   396  	key = rangeConvert(n, n.Key.Type(), key, n.KeyTypeWord, n.KeySrcRType)
   397  	value = rangeConvert(n, n.Value.Type(), value, n.ValueTypeWord, n.ValueSrcRType)
   398  	return ir.NewAssignListStmt(n.Pos(), ir.OAS2, []ir.Node{n.Key, n.Value}, []ir.Node{key, value})
   399  }
   400  
   401  // rangeConvert returns src, converted to dst if necessary. If a
   402  // conversion is necessary, then typeWord and srcRType are copied to
   403  // their respective ConvExpr fields.
   404  func rangeConvert(nrange *ir.RangeStmt, dst *types.Type, src, typeWord, srcRType ir.Node) ir.Node {
   405  	src = typecheck.Expr(src)
   406  	if dst.Kind() == types.TBLANK || types.Identical(dst, src.Type()) {
   407  		return src
   408  	}
   409  
   410  	n := ir.NewConvExpr(nrange.Pos(), ir.OCONV, dst, src)
   411  	n.TypeWord = typeWord
   412  	n.SrcRType = srcRType
   413  	return typecheck.Expr(n)
   414  }
   415  
   416  // isMapClear checks if n is of the form:
   417  //
   418  //	for k := range m {
   419  //		delete(m, k)
   420  //	}
   421  //
   422  // where == for keys of map m is reflexive.
   423  func isMapClear(n *ir.RangeStmt) bool {
   424  	if base.Flag.N != 0 || base.Flag.Cfg.Instrumenting {
   425  		return false
   426  	}
   427  
   428  	t := n.X.Type()
   429  	if n.Op() != ir.ORANGE || t.Kind() != types.TMAP || n.Key == nil || n.Value != nil {
   430  		return false
   431  	}
   432  
   433  	k := n.Key
   434  	// Require k to be a new variable name.
   435  	if !ir.DeclaredBy(k, n) {
   436  		return false
   437  	}
   438  
   439  	if len(n.Body) != 1 {
   440  		return false
   441  	}
   442  
   443  	stmt := n.Body[0] // only stmt in body
   444  	if stmt == nil || stmt.Op() != ir.ODELETE {
   445  		return false
   446  	}
   447  
   448  	m := n.X
   449  	if delete := stmt.(*ir.CallExpr); !ir.SameSafeExpr(delete.Args[0], m) || !ir.SameSafeExpr(delete.Args[1], k) {
   450  		return false
   451  	}
   452  
   453  	// Keys where equality is not reflexive can not be deleted from maps.
   454  	if !types.IsReflexive(t.Key()) {
   455  		return false
   456  	}
   457  
   458  	return true
   459  }
   460  
   461  // mapRangeClear constructs a call to runtime.mapclear for the map range idiom.
   462  func mapRangeClear(nrange *ir.RangeStmt) ir.Node {
   463  	m := nrange.X
   464  	origPos := ir.SetPos(m)
   465  	defer func() { base.Pos = origPos }()
   466  
   467  	return mapClear(m, reflectdata.RangeMapRType(base.Pos, nrange))
   468  }
   469  
   470  // mapClear constructs a call to runtime.mapclear for the map m.
   471  func mapClear(m, rtyp ir.Node) ir.Node {
   472  	t := m.Type()
   473  
   474  	// instantiate mapclear(typ *type, hmap map[any]any)
   475  	fn := typecheck.LookupRuntime("mapclear", t.Key(), t.Elem())
   476  	n := mkcallstmt1(fn, rtyp, m)
   477  	return walkStmt(typecheck.Stmt(n))
   478  }
   479  
   480  // Lower n into runtime·memclr if possible, for
   481  // fast zeroing of slices and arrays (issue 5373).
   482  // Look for instances of
   483  //
   484  //	for i := range a {
   485  //		a[i] = zero
   486  //	}
   487  //
   488  // in which the evaluation of a is side-effect-free.
   489  //
   490  // Parameters are as in walkRange: "for v1, v2 = range a".
   491  func arrayRangeClear(loop *ir.RangeStmt, v1, v2, a ir.Node) ir.Node {
   492  	if base.Flag.N != 0 || base.Flag.Cfg.Instrumenting {
   493  		return nil
   494  	}
   495  
   496  	if v1 == nil || v2 != nil {
   497  		return nil
   498  	}
   499  
   500  	if len(loop.Body) != 1 || loop.Body[0] == nil {
   501  		return nil
   502  	}
   503  
   504  	stmt1 := loop.Body[0] // only stmt in body
   505  	if stmt1.Op() != ir.OAS {
   506  		return nil
   507  	}
   508  	stmt := stmt1.(*ir.AssignStmt)
   509  	if stmt.X.Op() != ir.OINDEX {
   510  		return nil
   511  	}
   512  	lhs := stmt.X.(*ir.IndexExpr)
   513  	x := lhs.X
   514  	if a.Type().IsPtr() && a.Type().Elem().IsArray() {
   515  		if s, ok := x.(*ir.StarExpr); ok && s.Op() == ir.ODEREF {
   516  			x = s.X
   517  		}
   518  	}
   519  
   520  	if !ir.SameSafeExpr(x, a) || !ir.SameSafeExpr(lhs.Index, v1) {
   521  		return nil
   522  	}
   523  
   524  	if !ir.IsZero(stmt.Y) {
   525  		return nil
   526  	}
   527  
   528  	return arrayClear(stmt.Pos(), a, loop)
   529  }
   530  
   531  // arrayClear constructs a call to runtime.memclr for fast zeroing of slices and arrays.
   532  func arrayClear(wbPos src.XPos, a ir.Node, nrange *ir.RangeStmt) ir.Node {
   533  	elemsize := typecheck.RangeExprType(a.Type()).Elem().Size()
   534  	if elemsize <= 0 {
   535  		return nil
   536  	}
   537  
   538  	// Convert to
   539  	// if len(a) != 0 {
   540  	// 	hp = &a[0]
   541  	// 	hn = len(a)*sizeof(elem(a))
   542  	// 	memclr{NoHeap,Has}Pointers(hp, hn)
   543  	// 	i = len(a) - 1
   544  	// }
   545  	n := ir.NewIfStmt(base.Pos, nil, nil, nil)
   546  	n.Cond = ir.NewBinaryExpr(base.Pos, ir.ONE, ir.NewUnaryExpr(base.Pos, ir.OLEN, a), ir.NewInt(base.Pos, 0))
   547  
   548  	// hp = &a[0]
   549  	hp := typecheck.TempAt(base.Pos, ir.CurFunc, types.Types[types.TUNSAFEPTR])
   550  
   551  	ix := ir.NewIndexExpr(base.Pos, a, ir.NewInt(base.Pos, 0))
   552  	ix.SetBounded(true)
   553  	addr := typecheck.ConvNop(typecheck.NodAddr(ix), types.Types[types.TUNSAFEPTR])
   554  	n.Body.Append(ir.NewAssignStmt(base.Pos, hp, addr))
   555  
   556  	// hn = len(a) * sizeof(elem(a))
   557  	hn := typecheck.TempAt(base.Pos, ir.CurFunc, types.Types[types.TUINTPTR])
   558  	mul := typecheck.Conv(ir.NewBinaryExpr(base.Pos, ir.OMUL, ir.NewUnaryExpr(base.Pos, ir.OLEN, a), ir.NewInt(base.Pos, elemsize)), types.Types[types.TUINTPTR])
   559  	n.Body.Append(ir.NewAssignStmt(base.Pos, hn, mul))
   560  
   561  	var fn ir.Node
   562  	if a.Type().Elem().HasPointers() {
   563  		// memclrHasPointers(hp, hn)
   564  		ir.CurFunc.SetWBPos(wbPos)
   565  		fn = mkcallstmt("memclrHasPointers", hp, hn)
   566  	} else {
   567  		// memclrNoHeapPointers(hp, hn)
   568  		fn = mkcallstmt("memclrNoHeapPointers", hp, hn)
   569  	}
   570  
   571  	n.Body.Append(fn)
   572  
   573  	// For array range clear, also set "i = len(a) - 1"
   574  	if nrange != nil {
   575  		idx := ir.NewAssignStmt(base.Pos, nrange.Key, ir.NewBinaryExpr(base.Pos, ir.OSUB, ir.NewUnaryExpr(base.Pos, ir.OLEN, a), ir.NewInt(base.Pos, 1)))
   576  		n.Body.Append(idx)
   577  	}
   578  
   579  	n.Cond = typecheck.Expr(n.Cond)
   580  	n.Cond = typecheck.DefaultLit(n.Cond, nil)
   581  	typecheck.Stmts(n.Body)
   582  	return walkStmt(n)
   583  }
   584  

View as plain text