Black Lives Matter. Support the Equal Justice Initiative.

Source file src/cmd/compile/internal/ssa/nilcheck.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/internal/objabi"
     9  	"cmd/internal/src"
    10  )
    11  
    12  // nilcheckelim eliminates unnecessary nil checks.
    13  // runs on machine-independent code.
    14  func nilcheckelim(f *Func) {
    15  	// A nil check is redundant if the same nil check was successful in a
    16  	// dominating block. The efficacy of this pass depends heavily on the
    17  	// efficacy of the cse pass.
    18  	sdom := f.Sdom()
    19  
    20  	// TODO: Eliminate more nil checks.
    21  	// We can recursively remove any chain of fixed offset calculations,
    22  	// i.e. struct fields and array elements, even with non-constant
    23  	// indices: x is non-nil iff x.a.b[i].c is.
    24  
    25  	type walkState int
    26  	const (
    27  		Work     walkState = iota // process nil checks and traverse to dominees
    28  		ClearPtr                  // forget the fact that ptr is nil
    29  	)
    30  
    31  	type bp struct {
    32  		block *Block // block, or nil in ClearPtr state
    33  		ptr   *Value // if non-nil, ptr that is to be cleared in ClearPtr state
    34  		op    walkState
    35  	}
    36  
    37  	work := make([]bp, 0, 256)
    38  	work = append(work, bp{block: f.Entry})
    39  
    40  	// map from value ID to bool indicating if value is known to be non-nil
    41  	// in the current dominator path being walked. This slice is updated by
    42  	// walkStates to maintain the known non-nil values.
    43  	nonNilValues := make([]bool, f.NumValues())
    44  
    45  	// make an initial pass identifying any non-nil values
    46  	for _, b := range f.Blocks {
    47  		for _, v := range b.Values {
    48  			// a value resulting from taking the address of a
    49  			// value, or a value constructed from an offset of a
    50  			// non-nil ptr (OpAddPtr) implies it is non-nil
    51  			// We also assume unsafe pointer arithmetic generates non-nil pointers. See #27180.
    52  			// We assume that SlicePtr is non-nil because we do a bounds check
    53  			// before the slice access (and all cap>0 slices have a non-nil ptr). See #30366.
    54  			if v.Op == OpAddr || v.Op == OpLocalAddr || v.Op == OpAddPtr || v.Op == OpOffPtr || v.Op == OpAdd32 || v.Op == OpAdd64 || v.Op == OpSub32 || v.Op == OpSub64 || v.Op == OpSlicePtr {
    55  				nonNilValues[v.ID] = true
    56  			}
    57  		}
    58  	}
    59  
    60  	for changed := true; changed; {
    61  		changed = false
    62  		for _, b := range f.Blocks {
    63  			for _, v := range b.Values {
    64  				// phis whose arguments are all non-nil
    65  				// are non-nil
    66  				if v.Op == OpPhi {
    67  					argsNonNil := true
    68  					for _, a := range v.Args {
    69  						if !nonNilValues[a.ID] {
    70  							argsNonNil = false
    71  							break
    72  						}
    73  					}
    74  					if argsNonNil {
    75  						if !nonNilValues[v.ID] {
    76  							changed = true
    77  						}
    78  						nonNilValues[v.ID] = true
    79  					}
    80  				}
    81  			}
    82  		}
    83  	}
    84  
    85  	// allocate auxiliary date structures for computing store order
    86  	sset := f.newSparseSet(f.NumValues())
    87  	defer f.retSparseSet(sset)
    88  	storeNumber := make([]int32, f.NumValues())
    89  
    90  	// perform a depth first walk of the dominee tree
    91  	for len(work) > 0 {
    92  		node := work[len(work)-1]
    93  		work = work[:len(work)-1]
    94  
    95  		switch node.op {
    96  		case Work:
    97  			b := node.block
    98  
    99  			// First, see if we're dominated by an explicit nil check.
   100  			if len(b.Preds) == 1 {
   101  				p := b.Preds[0].b
   102  				if p.Kind == BlockIf && p.Controls[0].Op == OpIsNonNil && p.Succs[0].b == b {
   103  					if ptr := p.Controls[0].Args[0]; !nonNilValues[ptr.ID] {
   104  						nonNilValues[ptr.ID] = true
   105  						work = append(work, bp{op: ClearPtr, ptr: ptr})
   106  					}
   107  				}
   108  			}
   109  
   110  			// Next, order values in the current block w.r.t. stores.
   111  			b.Values = storeOrder(b.Values, sset, storeNumber)
   112  
   113  			pendingLines := f.cachedLineStarts // Holds statement boundaries that need to be moved to a new value/block
   114  			pendingLines.clear()
   115  
   116  			// Next, process values in the block.
   117  			i := 0
   118  			for _, v := range b.Values {
   119  				b.Values[i] = v
   120  				i++
   121  				switch v.Op {
   122  				case OpIsNonNil:
   123  					ptr := v.Args[0]
   124  					if nonNilValues[ptr.ID] {
   125  						if v.Pos.IsStmt() == src.PosIsStmt { // Boolean true is a terrible statement boundary.
   126  							pendingLines.add(v.Pos)
   127  							v.Pos = v.Pos.WithNotStmt()
   128  						}
   129  						// This is a redundant explicit nil check.
   130  						v.reset(OpConstBool)
   131  						v.AuxInt = 1 // true
   132  					}
   133  				case OpNilCheck:
   134  					ptr := v.Args[0]
   135  					if nonNilValues[ptr.ID] {
   136  						// This is a redundant implicit nil check.
   137  						// Logging in the style of the former compiler -- and omit line 1,
   138  						// which is usually in generated code.
   139  						if f.fe.Debug_checknil() && v.Pos.Line() > 1 {
   140  							f.Warnl(v.Pos, "removed nil check")
   141  						}
   142  						if v.Pos.IsStmt() == src.PosIsStmt { // About to lose a statement boundary
   143  							pendingLines.add(v.Pos)
   144  						}
   145  						v.reset(OpUnknown)
   146  						f.freeValue(v)
   147  						i--
   148  						continue
   149  					}
   150  					// Record the fact that we know ptr is non nil, and remember to
   151  					// undo that information when this dominator subtree is done.
   152  					nonNilValues[ptr.ID] = true
   153  					work = append(work, bp{op: ClearPtr, ptr: ptr})
   154  					fallthrough // a non-eliminated nil check might be a good place for a statement boundary.
   155  				default:
   156  					if v.Pos.IsStmt() != src.PosNotStmt && !isPoorStatementOp(v.Op) && pendingLines.contains(v.Pos) {
   157  						v.Pos = v.Pos.WithIsStmt()
   158  						pendingLines.remove(v.Pos)
   159  					}
   160  				}
   161  			}
   162  			// This reduces the lost statement count in "go" by 5 (out of 500 total).
   163  			for j := 0; j < i; j++ { // is this an ordering problem?
   164  				v := b.Values[j]
   165  				if v.Pos.IsStmt() != src.PosNotStmt && !isPoorStatementOp(v.Op) && pendingLines.contains(v.Pos) {
   166  					v.Pos = v.Pos.WithIsStmt()
   167  					pendingLines.remove(v.Pos)
   168  				}
   169  			}
   170  			if pendingLines.contains(b.Pos) {
   171  				b.Pos = b.Pos.WithIsStmt()
   172  				pendingLines.remove(b.Pos)
   173  			}
   174  			b.truncateValues(i)
   175  
   176  			// Add all dominated blocks to the work list.
   177  			for w := sdom[node.block.ID].child; w != nil; w = sdom[w.ID].sibling {
   178  				work = append(work, bp{op: Work, block: w})
   179  			}
   180  
   181  		case ClearPtr:
   182  			nonNilValues[node.ptr.ID] = false
   183  			continue
   184  		}
   185  	}
   186  }
   187  
   188  // All platforms are guaranteed to fault if we load/store to anything smaller than this address.
   189  //
   190  // This should agree with minLegalPointer in the runtime.
   191  const minZeroPage = 4096
   192  
   193  // faultOnLoad is true if a load to an address below minZeroPage will trigger a SIGSEGV.
   194  var faultOnLoad = objabi.GOOS != "aix"
   195  
   196  // nilcheckelim2 eliminates unnecessary nil checks.
   197  // Runs after lowering and scheduling.
   198  func nilcheckelim2(f *Func) {
   199  	unnecessary := f.newSparseMap(f.NumValues()) // map from pointer that will be dereferenced to index of dereferencing value in b.Values[]
   200  	defer f.retSparseMap(unnecessary)
   201  
   202  	pendingLines := f.cachedLineStarts // Holds statement boundaries that need to be moved to a new value/block
   203  
   204  	for _, b := range f.Blocks {
   205  		// Walk the block backwards. Find instructions that will fault if their
   206  		// input pointer is nil. Remove nil checks on those pointers, as the
   207  		// faulting instruction effectively does the nil check for free.
   208  		unnecessary.clear()
   209  		pendingLines.clear()
   210  		// Optimization: keep track of removed nilcheck with smallest index
   211  		firstToRemove := len(b.Values)
   212  		for i := len(b.Values) - 1; i >= 0; i-- {
   213  			v := b.Values[i]
   214  			if opcodeTable[v.Op].nilCheck && unnecessary.contains(v.Args[0].ID) {
   215  				if f.fe.Debug_checknil() && v.Pos.Line() > 1 {
   216  					f.Warnl(v.Pos, "removed nil check")
   217  				}
   218  				// For bug 33724, policy is that we might choose to bump an existing position
   219  				// off the faulting load/store in favor of the one from the nil check.
   220  
   221  				// Iteration order means that first nilcheck in the chain wins, others
   222  				// are bumped into the ordinary statement preservation algorithm.
   223  				u := b.Values[unnecessary.get(v.Args[0].ID)]
   224  				if !u.Pos.SameFileAndLine(v.Pos) {
   225  					if u.Pos.IsStmt() == src.PosIsStmt {
   226  						pendingLines.add(u.Pos)
   227  					}
   228  					u.Pos = v.Pos
   229  				} else if v.Pos.IsStmt() == src.PosIsStmt {
   230  					pendingLines.add(v.Pos)
   231  				}
   232  
   233  				v.reset(OpUnknown)
   234  				firstToRemove = i
   235  				continue
   236  			}
   237  			if v.Type.IsMemory() || v.Type.IsTuple() && v.Type.FieldType(1).IsMemory() {
   238  				if v.Op == OpVarKill || v.Op == OpVarLive || (v.Op == OpVarDef && !v.Aux.(GCNode).Typ().HasPointers()) {
   239  					// These ops don't really change memory.
   240  					continue
   241  					// Note: OpVarDef requires that the defined variable not have pointers.
   242  					// We need to make sure that there's no possible faulting
   243  					// instruction between a VarDef and that variable being
   244  					// fully initialized. If there was, then anything scanning
   245  					// the stack during the handling of that fault will see
   246  					// a live but uninitialized pointer variable on the stack.
   247  					//
   248  					// If we have:
   249  					//
   250  					//   NilCheck p
   251  					//   VarDef x
   252  					//   x = *p
   253  					//
   254  					// We can't rewrite that to
   255  					//
   256  					//   VarDef x
   257  					//   NilCheck p
   258  					//   x = *p
   259  					//
   260  					// Particularly, even though *p faults on p==nil, we still
   261  					// have to do the explicit nil check before the VarDef.
   262  					// See issue #32288.
   263  				}
   264  				// This op changes memory.  Any faulting instruction after v that
   265  				// we've recorded in the unnecessary map is now obsolete.
   266  				unnecessary.clear()
   267  			}
   268  
   269  			// Find any pointers that this op is guaranteed to fault on if nil.
   270  			var ptrstore [2]*Value
   271  			ptrs := ptrstore[:0]
   272  			if opcodeTable[v.Op].faultOnNilArg0 && (faultOnLoad || v.Type.IsMemory()) {
   273  				// On AIX, only writing will fault.
   274  				ptrs = append(ptrs, v.Args[0])
   275  			}
   276  			if opcodeTable[v.Op].faultOnNilArg1 && (faultOnLoad || (v.Type.IsMemory() && v.Op != OpPPC64LoweredMove)) {
   277  				// On AIX, only writing will fault.
   278  				// LoweredMove is a special case because it's considered as a "mem" as it stores on arg0 but arg1 is accessed as a load and should be checked.
   279  				ptrs = append(ptrs, v.Args[1])
   280  			}
   281  
   282  			for _, ptr := range ptrs {
   283  				// Check to make sure the offset is small.
   284  				switch opcodeTable[v.Op].auxType {
   285  				case auxSym:
   286  					if v.Aux != nil {
   287  						continue
   288  					}
   289  				case auxSymOff:
   290  					if v.Aux != nil || v.AuxInt < 0 || v.AuxInt >= minZeroPage {
   291  						continue
   292  					}
   293  				case auxSymValAndOff:
   294  					off := ValAndOff(v.AuxInt).Off()
   295  					if v.Aux != nil || off < 0 || off >= minZeroPage {
   296  						continue
   297  					}
   298  				case auxInt32:
   299  					// Mips uses this auxType for atomic add constant. It does not affect the effective address.
   300  				case auxInt64:
   301  					// ARM uses this auxType for duffcopy/duffzero/alignment info.
   302  					// It does not affect the effective address.
   303  				case auxNone:
   304  					// offset is zero.
   305  				default:
   306  					v.Fatalf("can't handle aux %s (type %d) yet\n", v.auxString(), int(opcodeTable[v.Op].auxType))
   307  				}
   308  				// This instruction is guaranteed to fault if ptr is nil.
   309  				// Any previous nil check op is unnecessary.
   310  				unnecessary.set(ptr.ID, int32(i), src.NoXPos)
   311  			}
   312  		}
   313  		// Remove values we've clobbered with OpUnknown.
   314  		i := firstToRemove
   315  		for j := i; j < len(b.Values); j++ {
   316  			v := b.Values[j]
   317  			if v.Op != OpUnknown {
   318  				if !notStmtBoundary(v.Op) && pendingLines.contains(v.Pos) { // Late in compilation, so any remaining NotStmt values are probably okay now.
   319  					v.Pos = v.Pos.WithIsStmt()
   320  					pendingLines.remove(v.Pos)
   321  				}
   322  				b.Values[i] = v
   323  				i++
   324  			}
   325  		}
   326  
   327  		if pendingLines.contains(b.Pos) {
   328  			b.Pos = b.Pos.WithIsStmt()
   329  		}
   330  
   331  		b.truncateValues(i)
   332  
   333  		// TODO: if b.Kind == BlockPlain, start the analysis in the subsequent block to find
   334  		// more unnecessary nil checks.  Would fix test/nilptr3.go:159.
   335  	}
   336  }
   337  

View as plain text