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

     1  // Copyright 2018 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  	"cmd/compile/internal/base"
     9  	"cmd/compile/internal/types"
    10  	"fmt"
    11  )
    12  
    13  type indVarFlags uint8
    14  
    15  const (
    16  	indVarMinExc    indVarFlags = 1 << iota // minimum value is exclusive (default: inclusive)
    17  	indVarMaxInc                            // maximum value is inclusive (default: exclusive)
    18  	indVarCountDown                         // if set the iteration starts at max and count towards min (default: min towards max)
    19  )
    20  
    21  type indVar struct {
    22  	ind   *Value // induction variable
    23  	nxt   *Value // the incremented variable
    24  	min   *Value // minimum value, inclusive/exclusive depends on flags
    25  	max   *Value // maximum value, inclusive/exclusive depends on flags
    26  	entry *Block // entry block in the loop.
    27  	flags indVarFlags
    28  	// Invariant: for all blocks strictly dominated by entry:
    29  	//	min <= ind <  max    [if flags == 0]
    30  	//	min <  ind <  max    [if flags == indVarMinExc]
    31  	//	min <= ind <= max    [if flags == indVarMaxInc]
    32  	//	min <  ind <= max    [if flags == indVarMinExc|indVarMaxInc]
    33  }
    34  
    35  // parseIndVar checks whether the SSA value passed as argument is a valid induction
    36  // variable, and, if so, extracts:
    37  //   - the minimum bound
    38  //   - the increment value
    39  //   - the "next" value (SSA value that is Phi'd into the induction variable every loop)
    40  //
    41  // Currently, we detect induction variables that match (Phi min nxt),
    42  // with nxt being (Add inc ind).
    43  // If it can't parse the induction variable correctly, it returns (nil, nil, nil).
    44  func parseIndVar(ind *Value) (min, inc, nxt *Value) {
    45  	if ind.Op != OpPhi {
    46  		return
    47  	}
    48  
    49  	if n := ind.Args[0]; (n.Op == OpAdd64 || n.Op == OpAdd32 || n.Op == OpAdd16 || n.Op == OpAdd8) && (n.Args[0] == ind || n.Args[1] == ind) {
    50  		min, nxt = ind.Args[1], n
    51  	} else if n := ind.Args[1]; (n.Op == OpAdd64 || n.Op == OpAdd32 || n.Op == OpAdd16 || n.Op == OpAdd8) && (n.Args[0] == ind || n.Args[1] == ind) {
    52  		min, nxt = ind.Args[0], n
    53  	} else {
    54  		// Not a recognized induction variable.
    55  		return
    56  	}
    57  
    58  	if nxt.Args[0] == ind { // nxt = ind + inc
    59  		inc = nxt.Args[1]
    60  	} else if nxt.Args[1] == ind { // nxt = inc + ind
    61  		inc = nxt.Args[0]
    62  	} else {
    63  		panic("unreachable") // one of the cases must be true from the above.
    64  	}
    65  
    66  	return
    67  }
    68  
    69  // findIndVar finds induction variables in a function.
    70  //
    71  // Look for variables and blocks that satisfy the following
    72  //
    73  //	 loop:
    74  //	   ind = (Phi min nxt),
    75  //	   if ind < max
    76  //	     then goto enter_loop
    77  //	     else goto exit_loop
    78  //
    79  //	   enter_loop:
    80  //		do something
    81  //	      nxt = inc + ind
    82  //		goto loop
    83  //
    84  //	 exit_loop:
    85  func findIndVar(f *Func) []indVar {
    86  	var iv []indVar
    87  	sdom := f.Sdom()
    88  
    89  	for _, b := range f.Blocks {
    90  		if b.Kind != BlockIf || len(b.Preds) != 2 {
    91  			continue
    92  		}
    93  
    94  		var ind *Value   // induction variable
    95  		var init *Value  // starting value
    96  		var limit *Value // ending value
    97  
    98  		// Check that the control if it either ind </<= limit or limit </<= ind.
    99  		// TODO: Handle unsigned comparisons?
   100  		c := b.Controls[0]
   101  		inclusive := false
   102  		switch c.Op {
   103  		case OpLeq64, OpLeq32, OpLeq16, OpLeq8:
   104  			inclusive = true
   105  			fallthrough
   106  		case OpLess64, OpLess32, OpLess16, OpLess8:
   107  			ind, limit = c.Args[0], c.Args[1]
   108  		default:
   109  			continue
   110  		}
   111  
   112  		// See if this is really an induction variable
   113  		less := true
   114  		init, inc, nxt := parseIndVar(ind)
   115  		if init == nil {
   116  			// We failed to parse the induction variable. Before punting, we want to check
   117  			// whether the control op was written with the induction variable on the RHS
   118  			// instead of the LHS. This happens for the downwards case, like:
   119  			//     for i := len(n)-1; i >= 0; i--
   120  			init, inc, nxt = parseIndVar(limit)
   121  			if init == nil {
   122  				// No recognized induction variable on either operand
   123  				continue
   124  			}
   125  
   126  			// Ok, the arguments were reversed. Swap them, and remember that we're
   127  			// looking at an ind >/>= loop (so the induction must be decrementing).
   128  			ind, limit = limit, ind
   129  			less = false
   130  		}
   131  
   132  		if ind.Block != b {
   133  			// TODO: Could be extended to include disjointed loop headers.
   134  			// I don't think this is causing missed optimizations in real world code often.
   135  			// See https://go.dev/issue/63955
   136  			continue
   137  		}
   138  
   139  		// Expect the increment to be a nonzero constant.
   140  		if !inc.isGenericIntConst() {
   141  			continue
   142  		}
   143  		step := inc.AuxInt
   144  		if step == 0 {
   145  			continue
   146  		}
   147  		// step == minInt64 cannot be safely negated below, because -step
   148  		// overflows back to minInt64. The later underflow checks need a
   149  		// positive magnitude, so reject this case here.
   150  		if step == minSignedValue(ind.Type) {
   151  			continue
   152  		}
   153  
   154  		// Increment sign must match comparison direction.
   155  		// When incrementing, the termination comparison must be ind </<= limit.
   156  		// When decrementing, the termination comparison must be ind >/>= limit.
   157  		// See issue 26116.
   158  		if step > 0 && !less {
   159  			continue
   160  		}
   161  		if step < 0 && less {
   162  			continue
   163  		}
   164  
   165  		// Up to now we extracted the induction variable (ind),
   166  		// the increment delta (inc), the temporary sum (nxt),
   167  		// the initial value (init) and the limiting value (limit).
   168  		//
   169  		// We also know that ind has the form (Phi init nxt) where
   170  		// nxt is (Add inc nxt) which means: 1) inc dominates nxt
   171  		// and 2) there is a loop starting at inc and containing nxt.
   172  		//
   173  		// We need to prove that the induction variable is incremented
   174  		// only when it's smaller than the limiting value.
   175  		// Two conditions must happen listed below to accept ind
   176  		// as an induction variable.
   177  
   178  		// First condition: loop entry has a single predecessor, which
   179  		// is the header block.  This implies that b.Succs[0] is
   180  		// reached iff ind < limit.
   181  		if len(b.Succs[0].b.Preds) != 1 {
   182  			// b.Succs[1] must exit the loop.
   183  			continue
   184  		}
   185  
   186  		// Second condition: b.Succs[0] dominates nxt so that
   187  		// nxt is computed when inc < limit.
   188  		if !sdom.IsAncestorEq(b.Succs[0].b, nxt.Block) {
   189  			// inc+ind can only be reached through the branch that enters the loop.
   190  			continue
   191  		}
   192  
   193  		// Check for overflow/underflow. We need to make sure that inc never causes
   194  		// the induction variable to wrap around.
   195  		// We use a function wrapper here for easy return true / return false / keep going logic.
   196  		// This function returns true if the increment will never overflow/underflow.
   197  		ok := func() bool {
   198  			if step > 0 {
   199  				if limit.isGenericIntConst() {
   200  					// Figure out the actual largest value.
   201  					v := limit.AuxInt
   202  					if !inclusive {
   203  						if v == minSignedValue(limit.Type) {
   204  							return false // < minint is never satisfiable.
   205  						}
   206  						v--
   207  					}
   208  					if init.isGenericIntConst() {
   209  						// Use stride to compute a better lower limit.
   210  						if init.AuxInt > v {
   211  							return false
   212  						}
   213  						// TODO(1.27): investigate passing a smaller-magnitude overflow limit to addU
   214  						// for addWillOverflow.
   215  						v = addU(init.AuxInt, diff(v, init.AuxInt)/uint64(step)*uint64(step))
   216  					}
   217  					if addWillOverflow(v, step, maxSignedValue(ind.Type)) {
   218  						return false
   219  					}
   220  					if inclusive && v != limit.AuxInt || !inclusive && v+1 != limit.AuxInt {
   221  						// We know a better limit than the programmer did. Use our limit instead.
   222  						limit = f.constVal(limit.Op, limit.Type, v, true)
   223  						inclusive = true
   224  					}
   225  					return true
   226  				}
   227  				if step == 1 && !inclusive {
   228  					// Can't overflow because maxint is never a possible value.
   229  					return true
   230  				}
   231  				// If the limit is not a constant, check to see if it is a
   232  				// negative offset from a known non-negative value.
   233  				knn, k := findKNN(limit)
   234  				if knn == nil || k < 0 {
   235  					return false
   236  				}
   237  				// limit == (something nonnegative) - k. That subtraction can't underflow, so
   238  				// we can trust it.
   239  				if inclusive {
   240  					// ind <= knn - k cannot overflow if step is at most k
   241  					return step <= k
   242  				}
   243  				// ind < knn - k cannot overflow if step is at most k+1
   244  				return step <= k+1 && k != maxSignedValue(limit.Type)
   245  			} else { // step < 0
   246  				if limit.isGenericIntConst() {
   247  					// Figure out the actual smallest value.
   248  					v := limit.AuxInt
   249  					if !inclusive {
   250  						if v == maxSignedValue(limit.Type) {
   251  							return false // > maxint is never satisfiable.
   252  						}
   253  						v++
   254  					}
   255  					if init.isGenericIntConst() {
   256  						// Use stride to compute a better lower limit.
   257  						if init.AuxInt < v {
   258  							return false
   259  						}
   260  						// TODO(1.27): investigate passing a smaller-magnitude underflow limit to subU
   261  						// for subWillUnderflow.
   262  						v = subU(init.AuxInt, diff(init.AuxInt, v)/uint64(-step)*uint64(-step))
   263  					}
   264  					if subWillUnderflow(v, -step, minSignedValue(ind.Type)) {
   265  						return false
   266  					}
   267  					if inclusive && v != limit.AuxInt || !inclusive && v-1 != limit.AuxInt {
   268  						// We know a better limit than the programmer did. Use our limit instead.
   269  						limit = f.constVal(limit.Op, limit.Type, v, true)
   270  						inclusive = true
   271  					}
   272  					return true
   273  				}
   274  				if step == -1 && !inclusive {
   275  					// Can't underflow because minint is never a possible value.
   276  					return true
   277  				}
   278  			}
   279  			return false
   280  
   281  		}
   282  
   283  		if ok() {
   284  			flags := indVarFlags(0)
   285  			var min, max *Value
   286  			if step > 0 {
   287  				min = init
   288  				max = limit
   289  				if inclusive {
   290  					flags |= indVarMaxInc
   291  				}
   292  			} else {
   293  				min = limit
   294  				max = init
   295  				flags |= indVarMaxInc
   296  				if !inclusive {
   297  					flags |= indVarMinExc
   298  				}
   299  				flags |= indVarCountDown
   300  				step = -step
   301  			}
   302  			if f.pass.debug >= 1 {
   303  				printIndVar(b, ind, min, max, step, flags)
   304  			}
   305  
   306  			iv = append(iv, indVar{
   307  				ind:   ind,
   308  				nxt:   nxt,
   309  				min:   min,
   310  				max:   max,
   311  				entry: b.Succs[0].b,
   312  				flags: flags,
   313  			})
   314  			b.Logf("found induction variable %v (inc = %v, min = %v, max = %v)\n", ind, inc, min, max)
   315  		}
   316  
   317  		// TODO: other unrolling idioms
   318  		// for i := 0; i < KNN - KNN % k ; i += k
   319  		// for i := 0; i < KNN&^(k-1) ; i += k // k a power of 2
   320  		// for i := 0; i < KNN&(-k) ; i += k // k a power of 2
   321  	}
   322  
   323  	return iv
   324  }
   325  
   326  // subWillUnderflow checks if x - y underflows the min value.
   327  // y must be positive.
   328  func subWillUnderflow(x, y int64, min int64) bool {
   329  	if y < 0 {
   330  		base.Fatalf("expecting positive value")
   331  	}
   332  	return x < min+y
   333  }
   334  
   335  // addWillOverflow checks if x + y overflows the max value.
   336  // y must be positive.
   337  func addWillOverflow(x, y int64, max int64) bool {
   338  	if y < 0 {
   339  		base.Fatalf("expecting positive value")
   340  	}
   341  	return x > max-y
   342  }
   343  
   344  // diff returns x-y as a uint64. Requires x>=y.
   345  func diff(x, y int64) uint64 {
   346  	if x < y {
   347  		base.Fatalf("diff %d - %d underflowed", x, y)
   348  	}
   349  	return uint64(x - y)
   350  }
   351  
   352  // addU returns x+y. Requires that x+y does not overflow an int64.
   353  func addU(x int64, y uint64) int64 {
   354  	if y >= 1<<63 {
   355  		if x >= 0 {
   356  			base.Fatalf("addU overflowed %d + %d", x, y)
   357  		}
   358  		x += 1<<63 - 1
   359  		x += 1
   360  		y -= 1 << 63
   361  	}
   362  	// TODO(1.27): investigate passing a smaller-magnitude overflow limit in here.
   363  	if addWillOverflow(x, int64(y), maxSignedValue(types.Types[types.TINT64])) {
   364  		base.Fatalf("addU overflowed %d + %d", x, y)
   365  	}
   366  	return x + int64(y)
   367  }
   368  
   369  // subU returns x-y. Requires that x-y does not underflow an int64.
   370  func subU(x int64, y uint64) int64 {
   371  	if y >= 1<<63 {
   372  		if x < 0 {
   373  			base.Fatalf("subU underflowed %d - %d", x, y)
   374  		}
   375  		x -= 1<<63 - 1
   376  		x -= 1
   377  		y -= 1 << 63
   378  	}
   379  	// TODO(1.27): investigate passing a smaller-magnitude underflow limit in here.
   380  	if subWillUnderflow(x, int64(y), minSignedValue(types.Types[types.TINT64])) {
   381  		base.Fatalf("subU underflowed %d - %d", x, y)
   382  	}
   383  	return x - int64(y)
   384  }
   385  
   386  // if v is known to be x - c, where x is known to be nonnegative and c is a
   387  // constant, return x, c. Otherwise return nil, 0.
   388  func findKNN(v *Value) (*Value, int64) {
   389  	var x, y *Value
   390  	x = v
   391  	switch v.Op {
   392  	case OpSub64, OpSub32, OpSub16, OpSub8:
   393  		x = v.Args[0]
   394  		y = v.Args[1]
   395  
   396  	case OpAdd64, OpAdd32, OpAdd16, OpAdd8:
   397  		x = v.Args[0]
   398  		y = v.Args[1]
   399  		if x.isGenericIntConst() {
   400  			x, y = y, x
   401  		}
   402  	}
   403  	switch x.Op {
   404  	case OpSliceLen, OpStringLen, OpSliceCap:
   405  	default:
   406  		return nil, 0
   407  	}
   408  	if y == nil {
   409  		return x, 0
   410  	}
   411  	if !y.isGenericIntConst() {
   412  		return nil, 0
   413  	}
   414  	if v.Op == OpAdd64 || v.Op == OpAdd32 || v.Op == OpAdd16 || v.Op == OpAdd8 {
   415  		return x, -y.AuxInt
   416  	}
   417  	return x, y.AuxInt
   418  }
   419  
   420  func printIndVar(b *Block, i, min, max *Value, inc int64, flags indVarFlags) {
   421  	mb1, mb2 := "[", "]"
   422  	if flags&indVarMinExc != 0 {
   423  		mb1 = "("
   424  	}
   425  	if flags&indVarMaxInc == 0 {
   426  		mb2 = ")"
   427  	}
   428  
   429  	mlim1, mlim2 := fmt.Sprint(min.AuxInt), fmt.Sprint(max.AuxInt)
   430  	if !min.isGenericIntConst() {
   431  		if b.Func.pass.debug >= 2 {
   432  			mlim1 = fmt.Sprint(min)
   433  		} else {
   434  			mlim1 = "?"
   435  		}
   436  	}
   437  	if !max.isGenericIntConst() {
   438  		if b.Func.pass.debug >= 2 {
   439  			mlim2 = fmt.Sprint(max)
   440  		} else {
   441  			mlim2 = "?"
   442  		}
   443  	}
   444  	extra := ""
   445  	if b.Func.pass.debug >= 2 {
   446  		extra = fmt.Sprintf(" (%s)", i)
   447  	}
   448  	b.Func.Warnl(b.Pos, "Induction variable: limits %v%v,%v%v, increment %d%s", mb1, mlim1, mlim2, mb2, inc, extra)
   449  }
   450  
   451  func minSignedValue(t *types.Type) int64 {
   452  	return -1 << (t.Size()*8 - 1)
   453  }
   454  
   455  func maxSignedValue(t *types.Type) int64 {
   456  	return 1<<((t.Size()*8)-1) - 1
   457  }
   458  

View as plain text