Black Lives Matter. Support the Equal Justice Initiative.

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

Documentation: cmd/compile/internal/ssa

     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  	"cmd/compile/internal/types"
     9  	"container/heap"
    10  	"sort"
    11  )
    12  
    13  const (
    14  	ScorePhi = iota // towards top of block
    15  	ScoreArg
    16  	ScoreNilCheck
    17  	ScoreReadTuple
    18  	ScoreVarDef
    19  	ScoreMemory
    20  	ScoreReadFlags
    21  	ScoreDefault
    22  	ScoreFlags
    23  	ScoreControl // towards bottom of block
    24  )
    25  
    26  type ValHeap struct {
    27  	a     []*Value
    28  	score []int8
    29  }
    30  
    31  func (h ValHeap) Len() int      { return len(h.a) }
    32  func (h ValHeap) Swap(i, j int) { a := h.a; a[i], a[j] = a[j], a[i] }
    33  
    34  func (h *ValHeap) Push(x interface{}) {
    35  	// Push and Pop use pointer receivers because they modify the slice's length,
    36  	// not just its contents.
    37  	v := x.(*Value)
    38  	h.a = append(h.a, v)
    39  }
    40  func (h *ValHeap) Pop() interface{} {
    41  	old := h.a
    42  	n := len(old)
    43  	x := old[n-1]
    44  	h.a = old[0 : n-1]
    45  	return x
    46  }
    47  func (h ValHeap) Less(i, j int) bool {
    48  	x := h.a[i]
    49  	y := h.a[j]
    50  	sx := h.score[x.ID]
    51  	sy := h.score[y.ID]
    52  	if c := sx - sy; c != 0 {
    53  		return c > 0 // higher score comes later.
    54  	}
    55  	if x.Pos != y.Pos { // Favor in-order line stepping
    56  		return x.Pos.After(y.Pos)
    57  	}
    58  	if x.Op != OpPhi {
    59  		if c := len(x.Args) - len(y.Args); c != 0 {
    60  			return c < 0 // smaller args comes later
    61  		}
    62  	}
    63  	if c := x.Uses - y.Uses; c != 0 {
    64  		return c < 0 // smaller uses come later
    65  	}
    66  	// These comparisons are fairly arbitrary.
    67  	// The goal here is stability in the face
    68  	// of unrelated changes elsewhere in the compiler.
    69  	if c := x.AuxInt - y.AuxInt; c != 0 {
    70  		return c > 0
    71  	}
    72  	if cmp := x.Type.Compare(y.Type); cmp != types.CMPeq {
    73  		return cmp == types.CMPgt
    74  	}
    75  	return x.ID > y.ID
    76  }
    77  
    78  func (op Op) isLoweredGetClosurePtr() bool {
    79  	switch op {
    80  	case OpAMD64LoweredGetClosurePtr, OpPPC64LoweredGetClosurePtr, OpARMLoweredGetClosurePtr, OpARM64LoweredGetClosurePtr,
    81  		Op386LoweredGetClosurePtr, OpMIPS64LoweredGetClosurePtr, OpS390XLoweredGetClosurePtr, OpMIPSLoweredGetClosurePtr,
    82  		OpRISCV64LoweredGetClosurePtr, OpWasmLoweredGetClosurePtr:
    83  		return true
    84  	}
    85  	return false
    86  }
    87  
    88  // Schedule the Values in each Block. After this phase returns, the
    89  // order of b.Values matters and is the order in which those values
    90  // will appear in the assembly output. For now it generates a
    91  // reasonable valid schedule using a priority queue. TODO(khr):
    92  // schedule smarter.
    93  func schedule(f *Func) {
    94  	// For each value, the number of times it is used in the block
    95  	// by values that have not been scheduled yet.
    96  	uses := make([]int32, f.NumValues())
    97  
    98  	// reusable priority queue
    99  	priq := new(ValHeap)
   100  
   101  	// "priority" for a value
   102  	score := make([]int8, f.NumValues())
   103  
   104  	// scheduling order. We queue values in this list in reverse order.
   105  	// A constant bound allows this to be stack-allocated. 64 is
   106  	// enough to cover almost every schedule call.
   107  	order := make([]*Value, 0, 64)
   108  
   109  	// maps mem values to the next live memory value
   110  	nextMem := make([]*Value, f.NumValues())
   111  	// additional pretend arguments for each Value. Used to enforce load/store ordering.
   112  	additionalArgs := make([][]*Value, f.NumValues())
   113  
   114  	for _, b := range f.Blocks {
   115  		// Compute score. Larger numbers are scheduled closer to the end of the block.
   116  		for _, v := range b.Values {
   117  			switch {
   118  			case v.Op.isLoweredGetClosurePtr():
   119  				// We also score GetLoweredClosurePtr as early as possible to ensure that the
   120  				// context register is not stomped. GetLoweredClosurePtr should only appear
   121  				// in the entry block where there are no phi functions, so there is no
   122  				// conflict or ambiguity here.
   123  				if b != f.Entry {
   124  					f.Fatalf("LoweredGetClosurePtr appeared outside of entry block, b=%s", b.String())
   125  				}
   126  				score[v.ID] = ScorePhi
   127  			case v.Op == OpAMD64LoweredNilCheck || v.Op == OpPPC64LoweredNilCheck ||
   128  				v.Op == OpARMLoweredNilCheck || v.Op == OpARM64LoweredNilCheck ||
   129  				v.Op == Op386LoweredNilCheck || v.Op == OpMIPS64LoweredNilCheck ||
   130  				v.Op == OpS390XLoweredNilCheck || v.Op == OpMIPSLoweredNilCheck ||
   131  				v.Op == OpRISCV64LoweredNilCheck || v.Op == OpWasmLoweredNilCheck:
   132  				// Nil checks must come before loads from the same address.
   133  				score[v.ID] = ScoreNilCheck
   134  			case v.Op == OpPhi:
   135  				// We want all the phis first.
   136  				score[v.ID] = ScorePhi
   137  			case v.Op == OpVarDef:
   138  				// We want all the vardefs next.
   139  				score[v.ID] = ScoreVarDef
   140  			case v.Op == OpArg:
   141  				// We want all the args as early as possible, for better debugging.
   142  				score[v.ID] = ScoreArg
   143  			case v.Type.IsMemory():
   144  				// Schedule stores as early as possible. This tends to
   145  				// reduce register pressure. It also helps make sure
   146  				// VARDEF ops are scheduled before the corresponding LEA.
   147  				score[v.ID] = ScoreMemory
   148  			case v.Op == OpSelect0 || v.Op == OpSelect1:
   149  				// Schedule the pseudo-op of reading part of a tuple
   150  				// immediately after the tuple-generating op, since
   151  				// this value is already live. This also removes its
   152  				// false dependency on the other part of the tuple.
   153  				// Also ensures tuple is never spilled.
   154  				score[v.ID] = ScoreReadTuple
   155  			case v.Type.IsFlags() || v.Type.IsTuple() && v.Type.FieldType(1).IsFlags():
   156  				// Schedule flag register generation as late as possible.
   157  				// This makes sure that we only have one live flags
   158  				// value at a time.
   159  				score[v.ID] = ScoreFlags
   160  			default:
   161  				score[v.ID] = ScoreDefault
   162  				// If we're reading flags, schedule earlier to keep flag lifetime short.
   163  				for _, a := range v.Args {
   164  					if a.Type.IsFlags() {
   165  						score[v.ID] = ScoreReadFlags
   166  					}
   167  				}
   168  			}
   169  		}
   170  	}
   171  
   172  	for _, b := range f.Blocks {
   173  		// Find store chain for block.
   174  		// Store chains for different blocks overwrite each other, so
   175  		// the calculated store chain is good only for this block.
   176  		for _, v := range b.Values {
   177  			if v.Op != OpPhi && v.Type.IsMemory() {
   178  				for _, w := range v.Args {
   179  					if w.Type.IsMemory() {
   180  						nextMem[w.ID] = v
   181  					}
   182  				}
   183  			}
   184  		}
   185  
   186  		// Compute uses.
   187  		for _, v := range b.Values {
   188  			if v.Op == OpPhi {
   189  				// If a value is used by a phi, it does not induce
   190  				// a scheduling edge because that use is from the
   191  				// previous iteration.
   192  				continue
   193  			}
   194  			for _, w := range v.Args {
   195  				if w.Block == b {
   196  					uses[w.ID]++
   197  				}
   198  				// Any load must come before the following store.
   199  				if !v.Type.IsMemory() && w.Type.IsMemory() {
   200  					// v is a load.
   201  					s := nextMem[w.ID]
   202  					if s == nil || s.Block != b {
   203  						continue
   204  					}
   205  					additionalArgs[s.ID] = append(additionalArgs[s.ID], v)
   206  					uses[v.ID]++
   207  				}
   208  			}
   209  		}
   210  
   211  		for _, c := range b.ControlValues() {
   212  			// Force the control values to be scheduled at the end,
   213  			// unless they are phi values (which must be first).
   214  			// OpArg also goes first -- if it is stack it register allocates
   215  			// to a LoadReg, if it is register it is from the beginning anyway.
   216  			if c.Op == OpPhi || c.Op == OpArg {
   217  				continue
   218  			}
   219  			score[c.ID] = ScoreControl
   220  
   221  			// Schedule values dependent on the control values at the end.
   222  			// This reduces the number of register spills. We don't find
   223  			// all values that depend on the controls, just values with a
   224  			// direct dependency. This is cheaper and in testing there
   225  			// was no difference in the number of spills.
   226  			for _, v := range b.Values {
   227  				if v.Op != OpPhi {
   228  					for _, a := range v.Args {
   229  						if a == c {
   230  							score[v.ID] = ScoreControl
   231  						}
   232  					}
   233  				}
   234  			}
   235  
   236  		}
   237  
   238  		// To put things into a priority queue
   239  		// The values that should come last are least.
   240  		priq.score = score
   241  		priq.a = priq.a[:0]
   242  
   243  		// Initialize priority queue with schedulable values.
   244  		for _, v := range b.Values {
   245  			if uses[v.ID] == 0 {
   246  				heap.Push(priq, v)
   247  			}
   248  		}
   249  
   250  		// Schedule highest priority value, update use counts, repeat.
   251  		order = order[:0]
   252  		tuples := make(map[ID][]*Value)
   253  		for priq.Len() > 0 {
   254  			// Find highest priority schedulable value.
   255  			// Note that schedule is assembled backwards.
   256  
   257  			v := heap.Pop(priq).(*Value)
   258  
   259  			// Add it to the schedule.
   260  			// Do not emit tuple-reading ops until we're ready to emit the tuple-generating op.
   261  			//TODO: maybe remove ReadTuple score above, if it does not help on performance
   262  			switch {
   263  			case v.Op == OpSelect0:
   264  				if tuples[v.Args[0].ID] == nil {
   265  					tuples[v.Args[0].ID] = make([]*Value, 2)
   266  				}
   267  				tuples[v.Args[0].ID][0] = v
   268  			case v.Op == OpSelect1:
   269  				if tuples[v.Args[0].ID] == nil {
   270  					tuples[v.Args[0].ID] = make([]*Value, 2)
   271  				}
   272  				tuples[v.Args[0].ID][1] = v
   273  			case v.Type.IsTuple() && tuples[v.ID] != nil:
   274  				if tuples[v.ID][1] != nil {
   275  					order = append(order, tuples[v.ID][1])
   276  				}
   277  				if tuples[v.ID][0] != nil {
   278  					order = append(order, tuples[v.ID][0])
   279  				}
   280  				delete(tuples, v.ID)
   281  				fallthrough
   282  			default:
   283  				order = append(order, v)
   284  			}
   285  
   286  			// Update use counts of arguments.
   287  			for _, w := range v.Args {
   288  				if w.Block != b {
   289  					continue
   290  				}
   291  				uses[w.ID]--
   292  				if uses[w.ID] == 0 {
   293  					// All uses scheduled, w is now schedulable.
   294  					heap.Push(priq, w)
   295  				}
   296  			}
   297  			for _, w := range additionalArgs[v.ID] {
   298  				uses[w.ID]--
   299  				if uses[w.ID] == 0 {
   300  					// All uses scheduled, w is now schedulable.
   301  					heap.Push(priq, w)
   302  				}
   303  			}
   304  		}
   305  		if len(order) != len(b.Values) {
   306  			f.Fatalf("schedule does not include all values in block %s", b)
   307  		}
   308  		for i := 0; i < len(b.Values); i++ {
   309  			b.Values[i] = order[len(b.Values)-1-i]
   310  		}
   311  	}
   312  
   313  	f.scheduled = true
   314  }
   315  
   316  // storeOrder orders values with respect to stores. That is,
   317  // if v transitively depends on store s, v is ordered after s,
   318  // otherwise v is ordered before s.
   319  // Specifically, values are ordered like
   320  //   store1
   321  //   NilCheck that depends on store1
   322  //   other values that depends on store1
   323  //   store2
   324  //   NilCheck that depends on store2
   325  //   other values that depends on store2
   326  //   ...
   327  // The order of non-store and non-NilCheck values are undefined
   328  // (not necessarily dependency order). This should be cheaper
   329  // than a full scheduling as done above.
   330  // Note that simple dependency order won't work: there is no
   331  // dependency between NilChecks and values like IsNonNil.
   332  // Auxiliary data structures are passed in as arguments, so
   333  // that they can be allocated in the caller and be reused.
   334  // This function takes care of reset them.
   335  func storeOrder(values []*Value, sset *sparseSet, storeNumber []int32) []*Value {
   336  	if len(values) == 0 {
   337  		return values
   338  	}
   339  
   340  	f := values[0].Block.Func
   341  
   342  	// find all stores
   343  
   344  	// Members of values that are store values.
   345  	// A constant bound allows this to be stack-allocated. 64 is
   346  	// enough to cover almost every storeOrder call.
   347  	stores := make([]*Value, 0, 64)
   348  	hasNilCheck := false
   349  	sset.clear() // sset is the set of stores that are used in other values
   350  	for _, v := range values {
   351  		if v.Type.IsMemory() {
   352  			stores = append(stores, v)
   353  			if v.Op == OpInitMem || v.Op == OpPhi {
   354  				continue
   355  			}
   356  			sset.add(v.MemoryArg().ID) // record that v's memory arg is used
   357  		}
   358  		if v.Op == OpNilCheck {
   359  			hasNilCheck = true
   360  		}
   361  	}
   362  	if len(stores) == 0 || !hasNilCheck && f.pass.name == "nilcheckelim" {
   363  		// there is no store, the order does not matter
   364  		return values
   365  	}
   366  
   367  	// find last store, which is the one that is not used by other stores
   368  	var last *Value
   369  	for _, v := range stores {
   370  		if !sset.contains(v.ID) {
   371  			if last != nil {
   372  				f.Fatalf("two stores live simultaneously: %v and %v", v, last)
   373  			}
   374  			last = v
   375  		}
   376  	}
   377  
   378  	// We assign a store number to each value. Store number is the
   379  	// index of the latest store that this value transitively depends.
   380  	// The i-th store in the current block gets store number 3*i. A nil
   381  	// check that depends on the i-th store gets store number 3*i+1.
   382  	// Other values that depends on the i-th store gets store number 3*i+2.
   383  	// Special case: 0 -- unassigned, 1 or 2 -- the latest store it depends
   384  	// is in the previous block (or no store at all, e.g. value is Const).
   385  	// First we assign the number to all stores by walking back the store chain,
   386  	// then assign the number to other values in DFS order.
   387  	count := make([]int32, 3*(len(stores)+1))
   388  	sset.clear() // reuse sparse set to ensure that a value is pushed to stack only once
   389  	for n, w := len(stores), last; n > 0; n-- {
   390  		storeNumber[w.ID] = int32(3 * n)
   391  		count[3*n]++
   392  		sset.add(w.ID)
   393  		if w.Op == OpInitMem || w.Op == OpPhi {
   394  			if n != 1 {
   395  				f.Fatalf("store order is wrong: there are stores before %v", w)
   396  			}
   397  			break
   398  		}
   399  		w = w.MemoryArg()
   400  	}
   401  	var stack []*Value
   402  	for _, v := range values {
   403  		if sset.contains(v.ID) {
   404  			// in sset means v is a store, or already pushed to stack, or already assigned a store number
   405  			continue
   406  		}
   407  		stack = append(stack, v)
   408  		sset.add(v.ID)
   409  
   410  		for len(stack) > 0 {
   411  			w := stack[len(stack)-1]
   412  			if storeNumber[w.ID] != 0 {
   413  				stack = stack[:len(stack)-1]
   414  				continue
   415  			}
   416  			if w.Op == OpPhi {
   417  				// Phi value doesn't depend on store in the current block.
   418  				// Do this early to avoid dependency cycle.
   419  				storeNumber[w.ID] = 2
   420  				count[2]++
   421  				stack = stack[:len(stack)-1]
   422  				continue
   423  			}
   424  
   425  			max := int32(0) // latest store dependency
   426  			argsdone := true
   427  			for _, a := range w.Args {
   428  				if a.Block != w.Block {
   429  					continue
   430  				}
   431  				if !sset.contains(a.ID) {
   432  					stack = append(stack, a)
   433  					sset.add(a.ID)
   434  					argsdone = false
   435  					break
   436  				}
   437  				if storeNumber[a.ID]/3 > max {
   438  					max = storeNumber[a.ID] / 3
   439  				}
   440  			}
   441  			if !argsdone {
   442  				continue
   443  			}
   444  
   445  			n := 3*max + 2
   446  			if w.Op == OpNilCheck {
   447  				n = 3*max + 1
   448  			}
   449  			storeNumber[w.ID] = n
   450  			count[n]++
   451  			stack = stack[:len(stack)-1]
   452  		}
   453  	}
   454  
   455  	// convert count to prefix sum of counts: count'[i] = sum_{j<=i} count[i]
   456  	for i := range count {
   457  		if i == 0 {
   458  			continue
   459  		}
   460  		count[i] += count[i-1]
   461  	}
   462  	if count[len(count)-1] != int32(len(values)) {
   463  		f.Fatalf("storeOrder: value is missing, total count = %d, values = %v", count[len(count)-1], values)
   464  	}
   465  
   466  	// place values in count-indexed bins, which are in the desired store order
   467  	order := make([]*Value, len(values))
   468  	for _, v := range values {
   469  		s := storeNumber[v.ID]
   470  		order[count[s-1]] = v
   471  		count[s-1]++
   472  	}
   473  
   474  	// Order nil checks in source order. We want the first in source order to trigger.
   475  	// If two are on the same line, we don't really care which happens first.
   476  	// See issue 18169.
   477  	if hasNilCheck {
   478  		start := -1
   479  		for i, v := range order {
   480  			if v.Op == OpNilCheck {
   481  				if start == -1 {
   482  					start = i
   483  				}
   484  			} else {
   485  				if start != -1 {
   486  					sort.Sort(bySourcePos(order[start:i]))
   487  					start = -1
   488  				}
   489  			}
   490  		}
   491  		if start != -1 {
   492  			sort.Sort(bySourcePos(order[start:]))
   493  		}
   494  	}
   495  
   496  	return order
   497  }
   498  
   499  type bySourcePos []*Value
   500  
   501  func (s bySourcePos) Len() int           { return len(s) }
   502  func (s bySourcePos) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
   503  func (s bySourcePos) Less(i, j int) bool { return s[i].Pos.Before(s[j].Pos) }
   504  

View as plain text