1 // Copyright 2013 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 // An optional pass for sanity-checking invariants of the SSA representation.
8 // Currently it checks CFG invariants but little at the instruction level.
9 10 import (
11 "bytes"
12 "fmt"
13 "go/ast"
14 "go/types"
15 "io"
16 "os"
17 "slices"
18 "strings"
19 )
20 21 type sanity struct {
22 reporter io.Writer
23 fn *Function
24 block *BasicBlock
25 instrs map[Instruction]unit
26 insane bool
27 }
28 29 // sanityCheck performs integrity checking of the SSA representation
30 // of the function fn (which must have been "built") and returns true
31 // if it was valid. Diagnostics are written to reporter if non-nil,
32 // os.Stderr otherwise. Some diagnostics are only warnings and do not
33 // imply a negative result.
34 //
35 // Sanity-checking is intended to facilitate the debugging of code
36 // transformation passes.
37 func sanityCheck(fn *Function, reporter io.Writer) bool {
38 if reporter == nil {
39 reporter = os.Stderr
40 }
41 return (&sanity{reporter: reporter}).checkFunction(fn)
42 }
43 44 // mustSanityCheck is like sanityCheck but panics instead of returning
45 // a negative result.
46 func mustSanityCheck(fn *Function, reporter io.Writer) {
47 if !sanityCheck(fn, reporter) {
48 fn.WriteTo(os.Stderr)
49 panic("SanityCheck failed")
50 }
51 }
52 53 func (s *sanity) diagnostic(prefix, format string, args ...any) {
54 fmt.Fprintf(s.reporter, "%s: function %s", prefix, s.fn)
55 if s.block != nil {
56 fmt.Fprintf(s.reporter, ", block %s", s.block)
57 }
58 io.WriteString(s.reporter, ": ")
59 fmt.Fprintf(s.reporter, format, args...)
60 io.WriteString(s.reporter, "\n")
61 }
62 63 func (s *sanity) errorf(format string, args ...any) {
64 s.insane = true
65 s.diagnostic("Error", format, args...)
66 }
67 68 func (s *sanity) warnf(format string, args ...any) {
69 s.diagnostic("Warning", format, args...)
70 }
71 72 // findDuplicate returns an arbitrary basic block that appeared more
73 // than once in blocks, or nil if all were unique.
74 func findDuplicate(blocks []*BasicBlock) *BasicBlock {
75 if len(blocks) < 2 {
76 return nil
77 }
78 if blocks[0] == blocks[1] {
79 return blocks[0]
80 }
81 // Slow path:
82 m := make(map[*BasicBlock]bool)
83 for _, b := range blocks {
84 if m[b] {
85 return b
86 }
87 m[b] = true
88 }
89 return nil
90 }
91 92 func (s *sanity) checkInstr(idx int, instr Instruction) {
93 switch instr := instr.(type) {
94 case *If, *Jump, *Return, *Panic:
95 s.errorf("control flow instruction not at end of block")
96 case *Phi:
97 if idx == 0 {
98 // It suffices to apply this check to just the first phi node.
99 if dup := findDuplicate(s.block.Preds); dup != nil {
100 s.errorf("phi node in block with duplicate predecessor %s", dup)
101 }
102 } else {
103 prev := s.block.Instrs[idx-1]
104 if _, ok := prev.(*Phi); !ok {
105 s.errorf("Phi instruction follows a non-Phi: %T", prev)
106 }
107 }
108 if ne, np := len(instr.Edges), len(s.block.Preds); ne != np {
109 s.errorf("phi node has %d edges but %d predecessors", ne, np)
110 111 } else {
112 for i, e := range instr.Edges {
113 if e == nil {
114 s.errorf("phi node '%s' has no value for edge #%d from %s", instr.Comment, i, s.block.Preds[i])
115 } else if !types.Identical(instr.typ, e.Type()) {
116 s.errorf("phi node '%s' has a different type (%s) for edge #%d from %s (%s)",
117 instr.Comment, instr.Type(), i, s.block.Preds[i], e.Type())
118 }
119 }
120 }
121 122 case *Alloc:
123 if !instr.Heap {
124 found := slices.Contains(s.fn.Locals, instr)
125 if !found {
126 s.errorf("local alloc %s = %s does not appear in Function.Locals", instr.Name(), instr)
127 }
128 }
129 130 case *BinOp:
131 case *Call:
132 if common := instr.Call; common.IsInvoke() {
133 if !types.IsInterface(common.Value.Type()) {
134 s.errorf("invoke on %s (%s) which is not an interface type (or type param)", common.Value, common.Value.Type())
135 }
136 }
137 case *ChangeInterface:
138 case *ChangeType:
139 case *SliceToArrayPointer:
140 case *Convert:
141 if from := instr.X.Type(); !isBasicConvTypes(from) {
142 if to := instr.Type(); !isBasicConvTypes(to) {
143 s.errorf("convert %s -> %s: at least one type must be basic (or all basic, []byte, or []rune)", from, to)
144 }
145 }
146 case *MultiConvert:
147 case *Defer:
148 case *Extract:
149 case *Field:
150 case *FieldAddr:
151 case *Go:
152 case *Index:
153 case *IndexAddr:
154 case *Lookup:
155 case *MakeChan:
156 case *MakeClosure:
157 numFree := len(instr.Fn.(*Function).FreeVars)
158 numBind := len(instr.Bindings)
159 if numFree != numBind {
160 s.errorf("MakeClosure has %d Bindings for function %s with %d free vars",
161 numBind, instr.Fn, numFree)
162 163 }
164 if recv := instr.Type().(*types.Signature).Recv(); recv != nil {
165 s.errorf("MakeClosure's type includes receiver %s", recv.Type())
166 }
167 168 case *MakeInterface:
169 case *MakeMap:
170 case *MakeSlice:
171 case *MapUpdate:
172 case *Next:
173 case *Range:
174 case *RunDefers:
175 case *Select:
176 case *Send:
177 case *Slice:
178 case *Store:
179 case *TypeAssert:
180 case *UnOp:
181 case *DebugRef:
182 // TODO(adonovan): implement checks.
183 default:
184 panic(fmt.Sprintf("Unknown instruction type: %T", instr))
185 }
186 187 if call, ok := instr.(CallInstruction); ok {
188 if call.Common().Signature() == nil {
189 s.errorf("nil signature: %s", call)
190 }
191 }
192 193 // Check that value-defining instructions have valid types
194 // and a valid referrer list.
195 if v, ok := instr.(Value); ok {
196 t := v.Type()
197 if t == nil {
198 s.errorf("no type: %s = %s", v.Name(), v)
199 } else if t == tRangeIter || t == tDeferStack {
200 // not a proper type; ignore.
201 } else if b, ok := t.Underlying().(*types.Basic); ok && b.Info()&types.IsUntyped != 0 {
202 s.errorf("instruction has 'untyped' result: %s = %s : %s", v.Name(), v, t)
203 }
204 s.checkReferrerList(v)
205 }
206 207 // Untyped constants are legal as instruction Operands(),
208 // for example:
209 // _ = "foo"[0]
210 // or:
211 // if wordsize==64 {...}
212 213 // All other non-Instruction Values can be found via their
214 // enclosing Function or Package.
215 }
216 217 func (s *sanity) checkFinalInstr(instr Instruction) {
218 switch instr := instr.(type) {
219 case *If:
220 if nsuccs := len(s.block.Succs); nsuccs != 2 {
221 s.errorf("If-terminated block has %d successors; expected 2", nsuccs)
222 return
223 }
224 if s.block.Succs[0] == s.block.Succs[1] {
225 s.errorf("If-instruction has same True, False target blocks: %s", s.block.Succs[0])
226 return
227 }
228 229 case *Jump:
230 if nsuccs := len(s.block.Succs); nsuccs != 1 {
231 s.errorf("Jump-terminated block has %d successors; expected 1", nsuccs)
232 return
233 }
234 235 case *Return:
236 if nsuccs := len(s.block.Succs); nsuccs != 0 {
237 s.errorf("Return-terminated block has %d successors; expected none", nsuccs)
238 return
239 }
240 if na, nf := len(instr.Results), s.fn.Signature.Results().Len(); nf != na {
241 s.errorf("%d-ary return in %d-ary function", na, nf)
242 }
243 244 case *Panic:
245 if nsuccs := len(s.block.Succs); nsuccs != 0 {
246 s.errorf("Panic-terminated block has %d successors; expected none", nsuccs)
247 return
248 }
249 250 default:
251 s.errorf("non-control flow instruction at end of block")
252 }
253 }
254 255 func (s *sanity) checkBlock(b *BasicBlock, index int) {
256 s.block = b
257 258 if b.Index != index {
259 s.errorf("block has incorrect Index %d", b.Index)
260 }
261 if b.parent != s.fn {
262 s.errorf("block has incorrect parent %s", b.parent)
263 }
264 265 // Check all blocks are reachable.
266 // (The entry block is always implicitly reachable,
267 // as is the Recover block, if any.)
268 if (index > 0 && b != b.parent.Recover) && len(b.Preds) == 0 {
269 s.warnf("unreachable block")
270 if b.Instrs == nil {
271 // Since this block is about to be pruned,
272 // tolerating transient problems in it
273 // simplifies other optimizations.
274 return
275 }
276 }
277 278 // Check predecessor and successor relations are dual,
279 // and that all blocks in CFG belong to same function.
280 for _, a := range b.Preds {
281 found := slices.Contains(a.Succs, b)
282 if !found {
283 s.errorf("expected successor edge in predecessor %s; found only: %s", a, a.Succs)
284 }
285 if a.parent != s.fn {
286 s.errorf("predecessor %s belongs to different function %s", a, a.parent)
287 }
288 }
289 for _, c := range b.Succs {
290 found := slices.Contains(c.Preds, b)
291 if !found {
292 s.errorf("expected predecessor edge in successor %s; found only: %s", c, c.Preds)
293 }
294 if c.parent != s.fn {
295 s.errorf("successor %s belongs to different function %s", c, c.parent)
296 }
297 }
298 299 // Check each instruction is sane.
300 n := len(b.Instrs)
301 if n == 0 {
302 s.errorf("basic block contains no instructions")
303 }
304 var rands [10]*Value // reuse storage
305 for j, instr := range b.Instrs {
306 if instr == nil {
307 s.errorf("nil instruction at index %d", j)
308 continue
309 }
310 if b2 := instr.Block(); b2 == nil {
311 s.errorf("nil Block() for instruction at index %d", j)
312 continue
313 } else if b2 != b {
314 s.errorf("wrong Block() (%s) for instruction at index %d ", b2, j)
315 continue
316 }
317 if j < n-1 {
318 s.checkInstr(j, instr)
319 } else {
320 s.checkFinalInstr(instr)
321 }
322 323 // Check Instruction.Operands.
324 operands:
325 for i, op := range instr.Operands(rands[:0]) {
326 if op == nil {
327 s.errorf("nil operand pointer %d of %s", i, instr)
328 continue
329 }
330 val := *op
331 if val == nil {
332 continue // a nil operand is ok
333 }
334 335 // Check that "untyped" types only appear on constant operands.
336 if _, ok := (*op).(*Const); !ok {
337 if basic, ok := (*op).Type().Underlying().(*types.Basic); ok {
338 if basic.Info()&types.IsUntyped != 0 {
339 s.errorf("operand #%d of %s is untyped: %s", i, instr, basic)
340 }
341 }
342 }
343 344 // Check that Operands that are also Instructions belong to same function.
345 // TODO(adonovan): also check their block dominates block b.
346 if val, ok := val.(Instruction); ok {
347 if val.Block() == nil {
348 s.errorf("operand %d of %s is an instruction (%s) that belongs to no block", i, instr, val)
349 } else if val.Parent() != s.fn {
350 s.errorf("operand %d of %s is an instruction (%s) from function %s", i, instr, val, val.Parent())
351 }
352 }
353 354 // Check that each function-local operand of
355 // instr refers back to instr. (NB: quadratic)
356 switch val := val.(type) {
357 case *Const, *Global, *Builtin:
358 continue // not local
359 case *Function:
360 if val.parent == nil {
361 continue // only anon functions are local
362 }
363 }
364 365 // TODO(adonovan): check val.Parent() != nil <=> val.Referrers() is defined.
366 367 if refs := val.Referrers(); refs != nil {
368 for _, ref := range *refs {
369 if ref == instr {
370 continue operands
371 }
372 }
373 s.errorf("operand %d of %s (%s) does not refer to us", i, instr, val)
374 } else {
375 s.errorf("operand %d of %s (%s) has no referrers", i, instr, val)
376 }
377 }
378 }
379 }
380 381 func (s *sanity) checkReferrerList(v Value) {
382 refs := v.Referrers()
383 if refs == nil {
384 s.errorf("%s has missing referrer list", v.Name())
385 return
386 }
387 for i, ref := range *refs {
388 if _, ok := s.instrs[ref]; !ok {
389 s.errorf("%s.Referrers()[%d] = %s is not an instruction belonging to this function", v.Name(), i, ref)
390 }
391 }
392 }
393 394 func (s *sanity) checkFunctionParams() {
395 signature := s.fn.Signature
396 params := s.fn.Params
397 398 // startSigParams is the start of signature.Params() within params.
399 startSigParams := 0
400 if signature.Recv() != nil {
401 startSigParams = 1
402 }
403 404 if startSigParams+signature.Params().Len() != len(params) {
405 s.errorf("function has %d parameters in signature but has %d after building",
406 startSigParams+signature.Params().Len(), len(params))
407 return
408 }
409 410 for i, param := range params {
411 var sigType types.Type
412 si := i - startSigParams
413 if si < 0 {
414 sigType = signature.Recv().Type()
415 } else {
416 sigType = signature.Params().At(si).Type()
417 }
418 419 if !types.Identical(sigType, param.Type()) {
420 s.errorf("expect type %s in signature but got type %s in param %d", param.Type(), sigType, i)
421 }
422 }
423 }
424 425 // checkTransientFields checks whether all transient fields of Function are cleared.
426 func (s *sanity) checkTransientFields() {
427 fn := s.fn
428 if fn.build != nil {
429 s.errorf("function transient field 'build' is not nil")
430 }
431 if fn.currentBlock != nil {
432 s.errorf("function transient field 'currentBlock' is not nil")
433 }
434 if fn.vars != nil {
435 s.errorf("function transient field 'vars' is not nil")
436 }
437 if fn.results != nil {
438 s.errorf("function transient field 'results' is not nil")
439 }
440 if fn.returnVars != nil {
441 s.errorf("function transient field 'returnVars' is not nil")
442 }
443 if fn.targets != nil {
444 s.errorf("function transient field 'targets' is not nil")
445 }
446 if fn.lblocks != nil {
447 s.errorf("function transient field 'lblocks' is not nil")
448 }
449 if fn.subst != nil {
450 s.errorf("function transient field 'subst' is not nil")
451 }
452 if fn.jump != nil {
453 s.errorf("function transient field 'jump' is not nil")
454 }
455 if fn.deferstack != nil {
456 s.errorf("function transient field 'deferstack' is not nil")
457 }
458 if fn.source != nil {
459 s.errorf("function transient field 'source' is not nil")
460 }
461 if fn.exits != nil {
462 s.errorf("function transient field 'exits' is not nil")
463 }
464 if fn.uniq != 0 {
465 s.errorf("function transient field 'uniq' is not zero")
466 }
467 }
468 469 func (s *sanity) checkFunction(fn *Function) bool {
470 s.fn = fn
471 s.checkFunctionParams()
472 s.checkTransientFields()
473 474 // TODO(taking): Sanity check origin, typeparams, and typeargs.
475 if fn.Prog == nil {
476 s.errorf("nil Prog")
477 }
478 479 var buf bytes.Buffer
480 _ = fn.String() // must not crash
481 _ = fn.RelString(fn.relPkg()) // must not crash
482 WriteFunction(&buf, fn) // must not crash
483 484 // All functions have a package, except delegates (which are
485 // shared across packages, or duplicated as weak symbols in a
486 // separate-compilation model), and error.Error.
487 if fn.Pkg == nil {
488 if strings.HasPrefix(fn.Synthetic, "from type information (on demand)") ||
489 strings.HasPrefix(fn.Synthetic, "wrapper ") ||
490 strings.HasPrefix(fn.Synthetic, "bound ") ||
491 strings.HasPrefix(fn.Synthetic, "thunk ") ||
492 strings.HasSuffix(fn.name, "Error") ||
493 strings.HasPrefix(fn.Synthetic, "instance ") ||
494 strings.HasPrefix(fn.Synthetic, "instantiation ") ||
495 (fn.parent != nil && len(fn.typeargs) > 0) /* anon fun in instance */ {
496 // ok
497 } else {
498 s.errorf("nil Pkg")
499 }
500 }
501 if src, syn := fn.Synthetic == "", fn.Syntax() != nil; src != syn {
502 if len(fn.typeargs) > 0 && fn.Prog.mode&InstantiateGenerics != 0 {
503 // ok (instantiation with InstantiateGenerics on)
504 } else if fn.topLevelOrigin != nil && len(fn.typeargs) > 0 {
505 // ok (we always have the syntax set for instantiation)
506 } else if _, rng := fn.syntax.(*ast.RangeStmt); rng && fn.Synthetic == "range-over-func yield" {
507 // ok (range-func-yields are both synthetic and keep syntax)
508 } else {
509 s.errorf("got fromSource=%t, hasSyntax=%t; want same values", src, syn)
510 }
511 }
512 513 // Build the set of valid referrers.
514 s.instrs = make(map[Instruction]unit)
515 516 // instrs are the instructions that are present in the function.
517 for instr := range fn.instrs() {
518 s.instrs[instr] = unit{}
519 }
520 521 // Check all Locals allocations appear in the function instruction.
522 for i, l := range fn.Locals {
523 if _, present := s.instrs[l]; !present {
524 s.warnf("function doesn't contain Local alloc %s", l.Name())
525 }
526 527 if l.Parent() != fn {
528 s.errorf("Local %s at index %d has wrong parent", l.Name(), i)
529 }
530 if l.Heap {
531 s.errorf("Local %s at index %d has Heap flag set", l.Name(), i)
532 }
533 }
534 for i, p := range fn.Params {
535 if p.Parent() != fn {
536 s.errorf("Param %s at index %d has wrong parent", p.Name(), i)
537 }
538 // Check common suffix of Signature and Params match type.
539 if sig := fn.Signature; sig != nil {
540 j := i - len(fn.Params) + sig.Params().Len() // index within sig.Params
541 if j < 0 {
542 continue
543 }
544 if !types.Identical(p.Type(), sig.Params().At(j).Type()) {
545 s.errorf("Param %s at index %d has wrong type (%s, versus %s in Signature)", p.Name(), i, p.Type(), sig.Params().At(j).Type())
546 547 }
548 }
549 s.checkReferrerList(p)
550 }
551 for i, fv := range fn.FreeVars {
552 if fv.Parent() != fn {
553 s.errorf("FreeVar %s at index %d has wrong parent", fv.Name(), i)
554 }
555 s.checkReferrerList(fv)
556 }
557 558 if fn.Blocks != nil && len(fn.Blocks) == 0 {
559 // Function _had_ blocks (so it's not external) but
560 // they were "optimized" away, even the entry block.
561 s.errorf("Blocks slice is non-nil but empty")
562 }
563 for i, b := range fn.Blocks {
564 if b == nil {
565 s.warnf("nil *BasicBlock at f.Blocks[%d]", i)
566 continue
567 }
568 s.checkBlock(b, i)
569 }
570 if fn.Recover != nil && fn.Blocks[fn.Recover.Index] != fn.Recover {
571 s.errorf("Recover block is not in Blocks slice")
572 }
573 574 s.block = nil
575 for i, anon := range fn.AnonFuncs {
576 if anon.Parent() != fn {
577 s.errorf("AnonFuncs[%d]=%s but %s.Parent()=%s", i, anon, anon, anon.Parent())
578 }
579 if i != int(anon.anonIdx) {
580 s.errorf("AnonFuncs[%d]=%s but %s.anonIdx=%d", i, anon, anon, anon.anonIdx)
581 }
582 }
583 s.fn = nil
584 return !s.insane
585 }
586 587 // sanityCheckPackage checks invariants of packages upon creation.
588 // It does not require that the package is built.
589 // Unlike sanityCheck (for functions), it just panics at the first error.
590 func sanityCheckPackage(pkg *Package) {
591 if pkg.Pkg == nil {
592 panic(fmt.Sprintf("Package %s has no Object", pkg))
593 }
594 if pkg.info != nil {
595 panic(fmt.Sprintf("package %s field 'info' is not cleared", pkg))
596 }
597 if pkg.files != nil {
598 panic(fmt.Sprintf("package %s field 'files' is not cleared", pkg))
599 }
600 if pkg.created != nil {
601 panic(fmt.Sprintf("package %s field 'created' is not cleared", pkg))
602 }
603 if pkg.initVersion != nil {
604 panic(fmt.Sprintf("package %s field 'initVersion' is not cleared", pkg))
605 }
606 607 _ = pkg.String() // must not crash
608 609 for name, mem := range pkg.Members {
610 if name != mem.Name() {
611 panic(fmt.Sprintf("%s: %T.Name() = %s, want %s",
612 pkg.Pkg.Path(), mem, mem.Name(), name))
613 }
614 obj := mem.Object()
615 if obj == nil {
616 // This check is sound because fields
617 // {Global,Function}.object have type
618 // types.Object. (If they were declared as
619 // *types.{Var,Func}, we'd have a non-empty
620 // interface containing a nil pointer.)
621 622 continue // not all members have typechecker objects
623 }
624 if obj.Name() != name {
625 if obj.Name() == "init" && strings.HasPrefix(mem.Name(), "init#") {
626 // Ok. The name of a declared init function varies between
627 // its types.Func ("init") and its ssa.Function ("init#%d").
628 } else {
629 panic(fmt.Sprintf("%s: %T.Object().Name() = %s, want %s",
630 pkg.Pkg.Path(), mem, obj.Name(), name))
631 }
632 }
633 if obj.Pos() != mem.Pos() {
634 panic(fmt.Sprintf("%s Pos=%d obj.Pos=%d", mem, mem.Pos(), obj.Pos()))
635 }
636 }
637 }
638