1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package inlheur
import (
"cmd/compile/internal/base"
"cmd/compile/internal/ir"
"cmd/compile/internal/types"
"fmt"
"os"
)
// funcFlagsAnalyzer computes the "Flags" value for the FuncProps
// object we're computing. The main item of interest here is "nstate",
// which stores the disposition of a given ir Node with respect to the
// flags/properties we're trying to compute.
type funcFlagsAnalyzer struct {
fn *ir.Func
nstate map[ir.Node]pstate
noInfo bool // set if we see something inscrutable/un-analyzable
}
// pstate keeps track of the disposition of a given node and its
// children with respect to panic/exit calls.
type pstate int
const (
psNoInfo pstate = iota // nothing interesting about this node
psCallsPanic // node causes call to panic or os.Exit
psMayReturn // executing node may trigger a "return" stmt
psTop // dataflow lattice "top" element
)
func makeFuncFlagsAnalyzer(fn *ir.Func) *funcFlagsAnalyzer {
return &funcFlagsAnalyzer{
fn: fn,
nstate: make(map[ir.Node]pstate),
}
}
// setResults transfers func flag results to 'funcProps'.
func (ffa *funcFlagsAnalyzer) setResults(funcProps *FuncProps) {
var rv FuncPropBits
if !ffa.noInfo && ffa.stateForList(ffa.fn.Body) == psCallsPanic {
rv = FuncPropNeverReturns
}
// This is slightly hacky and not at all required, but include a
// special case for main.main, which often ends in a call to
// os.Exit. People who write code like this (very common I
// imagine)
//
// func main() {
// rc = perform()
// ...
// foo()
// os.Exit(rc)
// }
//
// will be constantly surprised when foo() is inlined in many
// other spots in the program but not in main().
if isMainMain(ffa.fn) {
rv &^= FuncPropNeverReturns
}
funcProps.Flags = rv
}
func (ffa *funcFlagsAnalyzer) getState(n ir.Node) pstate {
return ffa.nstate[n]
}
func (ffa *funcFlagsAnalyzer) setState(n ir.Node, st pstate) {
if st != psNoInfo {
ffa.nstate[n] = st
}
}
func (ffa *funcFlagsAnalyzer) updateState(n ir.Node, st pstate) {
if st == psNoInfo {
delete(ffa.nstate, n)
} else {
ffa.nstate[n] = st
}
}
func (ffa *funcFlagsAnalyzer) panicPathTable() map[ir.Node]pstate {
return ffa.nstate
}
// blockCombine merges together states as part of a linear sequence of
// statements, where 'pred' and 'succ' are analysis results for a pair
// of consecutive statements. Examples:
//
// case 1: case 2:
// panic("foo") if q { return x } <-pred
// return x panic("boo") <-succ
//
// In case 1, since the pred state is "always panic" it doesn't matter
// what the succ state is, hence the state for the combination of the
// two blocks is "always panics". In case 2, because there is a path
// to return that avoids the panic in succ, the state for the
// combination of the two statements is "may return".
func blockCombine(pred, succ pstate) pstate {
switch succ {
case psTop:
return pred
case psMayReturn:
if pred == psCallsPanic {
return psCallsPanic
}
return psMayReturn
case psNoInfo:
return pred
case psCallsPanic:
if pred == psMayReturn {
return psMayReturn
}
return psCallsPanic
}
panic("should never execute")
}
// branchCombine combines two states at a control flow branch point where
// either p1 or p2 executes (as in an "if" statement).
func branchCombine(p1, p2 pstate) pstate {
if p1 == psCallsPanic && p2 == psCallsPanic {
return psCallsPanic
}
if p1 == psMayReturn || p2 == psMayReturn {
return psMayReturn
}
return psNoInfo
}
// stateForList walks through a list of statements and computes the
// state/diposition for the entire list as a whole, as well
// as updating disposition of intermediate nodes.
func (ffa *funcFlagsAnalyzer) stateForList(list ir.Nodes) pstate {
st := psTop
// Walk the list backwards so that we can update the state for
// earlier list elements based on what we find out about their
// successors. Example:
//
// if ... {
// L10: foo()
// L11: <stmt>
// L12: panic(...)
// }
//
// After combining the dispositions for line 11 and 12, we want to
// update the state for the call at line 10 based on that combined
// disposition (if L11 has no path to "return", then the call at
// line 10 will be on a panic path).
for i := len(list) - 1; i >= 0; i-- {
n := list[i]
psi := ffa.getState(n)
if debugTrace&debugTraceFuncFlags != 0 {
fmt.Fprintf(os.Stderr, "=-= %v: stateForList n=%s ps=%s\n",
ir.Line(n), n.Op().String(), psi.String())
}
st = blockCombine(psi, st)
ffa.updateState(n, st)
}
if st == psTop {
st = psNoInfo
}
return st
}
func isMainMain(fn *ir.Func) bool {
s := fn.Sym()
return (s.Pkg.Name == "main" && s.Name == "main")
}
func isWellKnownFunc(s *types.Sym, pkg, name string) bool {
return s.Pkg.Path == pkg && s.Name == name
}
// isExitCall reports TRUE if the node itself is an unconditional
// call to os.Exit(), a panic, or a function that does likewise.
func isExitCall(n ir.Node) bool {
if n.Op() != ir.OCALLFUNC {
return false
}
cx := n.(*ir.CallExpr)
name := ir.StaticCalleeName(cx.Fun)
if name == nil {
return false
}
s := name.Sym()
if isWellKnownFunc(s, "os", "Exit") ||
isWellKnownFunc(s, "runtime", "throw") {
return true
}
if funcProps := propsForFunc(name.Func); funcProps != nil {
if funcProps.Flags&FuncPropNeverReturns != 0 {
return true
}
}
return name.Func.NeverReturns()
}
// pessimize is called to record the fact that we saw something in the
// function that renders it entirely impossible to analyze.
func (ffa *funcFlagsAnalyzer) pessimize() {
ffa.noInfo = true
}
// shouldVisit reports TRUE if this is an interesting node from the
// perspective of computing function flags. NB: due to the fact that
// ir.CallExpr implements the Stmt interface, we wind up visiting
// a lot of nodes that we don't really need to, but these can
// simply be screened out as part of the visit.
func shouldVisit(n ir.Node) bool {
_, isStmt := n.(ir.Stmt)
return n.Op() != ir.ODCL &&
(isStmt || n.Op() == ir.OCALLFUNC || n.Op() == ir.OPANIC)
}
// nodeVisitPost helps implement the propAnalyzer interface; when
// called on a given node, it decides the disposition of that node
// based on the state(s) of the node's children.
func (ffa *funcFlagsAnalyzer) nodeVisitPost(n ir.Node) {
if debugTrace&debugTraceFuncFlags != 0 {
fmt.Fprintf(os.Stderr, "=+= nodevis %v %s should=%v\n",
ir.Line(n), n.Op().String(), shouldVisit(n))
}
if !shouldVisit(n) {
return
}
var st pstate
switch n.Op() {
case ir.OCALLFUNC:
if isExitCall(n) {
st = psCallsPanic
}
case ir.OPANIC:
st = psCallsPanic
case ir.ORETURN:
st = psMayReturn
case ir.OBREAK, ir.OCONTINUE:
// FIXME: this handling of break/continue is sub-optimal; we
// have them as "mayReturn" in order to help with this case:
//
// for {
// if q() { break }
// panic(...)
// }
//
// where the effect of the 'break' is to cause the subsequent
// panic to be skipped. One possible improvement would be to
// track whether the currently enclosing loop is a "for {" or
// a for/range with condition, then use mayReturn only for the
// former. Note also that "break X" or "continue X" is treated
// the same as "goto", since we don't have a good way to track
// the target of the branch.
st = psMayReturn
n := n.(*ir.BranchStmt)
if n.Label != nil {
ffa.pessimize()
}
case ir.OBLOCK:
n := n.(*ir.BlockStmt)
st = ffa.stateForList(n.List)
case ir.OCASE:
if ccst, ok := n.(*ir.CaseClause); ok {
st = ffa.stateForList(ccst.Body)
} else if ccst, ok := n.(*ir.CommClause); ok {
st = ffa.stateForList(ccst.Body)
} else {
panic("unexpected")
}
case ir.OIF:
n := n.(*ir.IfStmt)
st = branchCombine(ffa.stateForList(n.Body), ffa.stateForList(n.Else))
case ir.OFOR:
// Treat for { XXX } like a block.
// Treat for <cond> { XXX } like an if statement with no else.
n := n.(*ir.ForStmt)
bst := ffa.stateForList(n.Body)
if n.Cond == nil {
st = bst
} else {
if bst == psMayReturn {
st = psMayReturn
}
}
case ir.ORANGE:
// Treat for range { XXX } like an if statement with no else.
n := n.(*ir.RangeStmt)
if ffa.stateForList(n.Body) == psMayReturn {
st = psMayReturn
}
case ir.OGOTO:
// punt if we see even one goto. if we built a control
// flow graph we could do more, but this is just a tree walk.
ffa.pessimize()
case ir.OSELECT:
// process selects for "may return" but not "always panics",
// the latter case seems very improbable.
n := n.(*ir.SelectStmt)
if len(n.Cases) != 0 {
st = psTop
for _, c := range n.Cases {
st = branchCombine(ffa.stateForList(c.Body), st)
}
}
case ir.OSWITCH:
n := n.(*ir.SwitchStmt)
if len(n.Cases) != 0 {
st = psTop
for _, c := range n.Cases {
st = branchCombine(ffa.stateForList(c.Body), st)
}
}
st, fall := psTop, psNoInfo
for i := len(n.Cases) - 1; i >= 0; i-- {
cas := n.Cases[i]
cst := ffa.stateForList(cas.Body)
endsInFallthrough := false
if len(cas.Body) != 0 {
endsInFallthrough = cas.Body[0].Op() == ir.OFALL
}
if endsInFallthrough {
cst = blockCombine(cst, fall)
}
st = branchCombine(st, cst)
fall = cst
}
case ir.OFALL:
// Not important.
case ir.ODCLFUNC, ir.ORECOVER, ir.OAS, ir.OAS2, ir.OAS2FUNC, ir.OASOP,
ir.OPRINTLN, ir.OPRINT, ir.OLABEL, ir.OCALLINTER, ir.ODEFER,
ir.OSEND, ir.ORECV, ir.OSELRECV2, ir.OGO, ir.OAPPEND, ir.OAS2DOTTYPE,
ir.OAS2MAPR, ir.OGETG, ir.ODELETE, ir.OINLMARK, ir.OAS2RECV,
ir.OMIN, ir.OMAX, ir.OMAKE, ir.ORECOVERFP, ir.OGETCALLERSP:
// these should all be benign/uninteresting
case ir.OTAILCALL, ir.OJUMPTABLE, ir.OTYPESW:
// don't expect to see these at all.
base.Fatalf("unexpected op %s in func %s",
n.Op().String(), ir.FuncName(ffa.fn))
default:
base.Fatalf("%v: unhandled op %s in func %v",
ir.Line(n), n.Op().String(), ir.FuncName(ffa.fn))
}
if debugTrace&debugTraceFuncFlags != 0 {
fmt.Fprintf(os.Stderr, "=-= %v: visit n=%s returns %s\n",
ir.Line(n), n.Op().String(), st.String())
}
ffa.setState(n, st)
}
func (ffa *funcFlagsAnalyzer) nodeVisitPre(n ir.Node) {
}
|