Debian Codegraph @

src/cmd/compile/internal/ssa/nilcheck.go

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