gitee.com/wgliang/goreporter@v0.0.0-20180902115603-df1b20f7c5d0/linters/simpler/ssa/sanity.go (about)

     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  // +build go1.5
     6  
     7  package ssa
     8  
     9  // An optional pass for sanity-checking invariants of the SSA representation.
    10  // Currently it checks CFG invariants but little at the instruction level.
    11  
    12  import (
    13  	"fmt"
    14  	"go/types"
    15  	"io"
    16  	"os"
    17  	"strings"
    18  )
    19  
    20  type sanity struct {
    21  	reporter io.Writer
    22  	fn       *Function
    23  	block    *BasicBlock
    24  	instrs   map[Instruction]struct{}
    25  	insane   bool
    26  }
    27  
    28  // sanityCheck performs integrity checking of the SSA representation
    29  // of the function fn and returns true if it was valid.  Diagnostics
    30  // are written to reporter if non-nil, os.Stderr otherwise.  Some
    31  // diagnostics are only warnings and do not imply a negative result.
    32  //
    33  // Sanity-checking is intended to facilitate the debugging of code
    34  // transformation passes.
    35  //
    36  func sanityCheck(fn *Function, reporter io.Writer) bool {
    37  	if reporter == nil {
    38  		reporter = os.Stderr
    39  	}
    40  	return (&sanity{reporter: reporter}).checkFunction(fn)
    41  }
    42  
    43  // mustSanityCheck is like sanityCheck but panics instead of returning
    44  // a negative result.
    45  //
    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 ...interface{}) {
    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 ...interface{}) {
    64  	s.insane = true
    65  	s.diagnostic("Error", format, args...)
    66  }
    67  
    68  func (s *sanity) warnf(format string, args ...interface{}) {
    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  				}
   116  			}
   117  		}
   118  
   119  	case *Alloc:
   120  		if !instr.Heap {
   121  			found := false
   122  			for _, l := range s.fn.Locals {
   123  				if l == instr {
   124  					found = true
   125  					break
   126  				}
   127  			}
   128  			if !found {
   129  				s.errorf("local alloc %s = %s does not appear in Function.Locals", instr.Name(), instr)
   130  			}
   131  		}
   132  
   133  	case *BinOp:
   134  	case *Call:
   135  	case *ChangeInterface:
   136  	case *ChangeType:
   137  	case *Convert:
   138  		if _, ok := instr.X.Type().Underlying().(*types.Basic); !ok {
   139  			if _, ok := instr.Type().Underlying().(*types.Basic); !ok {
   140  				s.errorf("convert %s -> %s: at least one type must be basic", instr.X.Type(), instr.Type())
   141  			}
   142  		}
   143  
   144  	case *Defer:
   145  	case *Extract:
   146  	case *Field:
   147  	case *FieldAddr:
   148  	case *Go:
   149  	case *Index:
   150  	case *IndexAddr:
   151  	case *Lookup:
   152  	case *MakeChan:
   153  	case *MakeClosure:
   154  		numFree := len(instr.Fn.(*Function).FreeVars)
   155  		numBind := len(instr.Bindings)
   156  		if numFree != numBind {
   157  			s.errorf("MakeClosure has %d Bindings for function %s with %d free vars",
   158  				numBind, instr.Fn, numFree)
   159  
   160  		}
   161  		if recv := instr.Type().(*types.Signature).Recv(); recv != nil {
   162  			s.errorf("MakeClosure's type includes receiver %s", recv.Type())
   163  		}
   164  
   165  	case *MakeInterface:
   166  	case *MakeMap:
   167  	case *MakeSlice:
   168  	case *MapUpdate:
   169  	case *Next:
   170  	case *Range:
   171  	case *RunDefers:
   172  	case *Select:
   173  	case *Send:
   174  	case *Slice:
   175  	case *Store:
   176  	case *TypeAssert:
   177  	case *UnOp:
   178  	case *DebugRef:
   179  	case *BlankStore:
   180  	case *Sigma:
   181  		// TODO(adonovan): implement checks.
   182  	default:
   183  		panic(fmt.Sprintf("Unknown instruction type: %T", instr))
   184  	}
   185  
   186  	if call, ok := instr.(CallInstruction); ok {
   187  		if call.Common().Signature() == nil {
   188  			s.errorf("nil signature: %s", call)
   189  		}
   190  	}
   191  
   192  	// Check that value-defining instructions have valid types
   193  	// and a valid referrer list.
   194  	if v, ok := instr.(Value); ok {
   195  		t := v.Type()
   196  		if t == nil {
   197  			s.errorf("no type: %s = %s", v.Name(), v)
   198  		} else if t == tRangeIter {
   199  			// not a proper type; ignore.
   200  		} else if b, ok := t.Underlying().(*types.Basic); ok && b.Info()&types.IsUntyped != 0 {
   201  			s.errorf("instruction has 'untyped' result: %s = %s : %s", v.Name(), v, t)
   202  		}
   203  		s.checkReferrerList(v)
   204  	}
   205  
   206  	// Untyped constants are legal as instruction Operands(),
   207  	// for example:
   208  	//   _ = "foo"[0]
   209  	// or:
   210  	//   if wordsize==64 {...}
   211  
   212  	// All other non-Instruction Values can be found via their
   213  	// enclosing Function or Package.
   214  }
   215  
   216  func (s *sanity) checkFinalInstr(idx int, instr Instruction) {
   217  	switch instr := instr.(type) {
   218  	case *If:
   219  		if nsuccs := len(s.block.Succs); nsuccs != 2 {
   220  			s.errorf("If-terminated block has %d successors; expected 2", nsuccs)
   221  			return
   222  		}
   223  		if s.block.Succs[0] == s.block.Succs[1] {
   224  			s.errorf("If-instruction has same True, False target blocks: %s", s.block.Succs[0])
   225  			return
   226  		}
   227  
   228  	case *Jump:
   229  		if nsuccs := len(s.block.Succs); nsuccs != 1 {
   230  			s.errorf("Jump-terminated block has %d successors; expected 1", nsuccs)
   231  			return
   232  		}
   233  
   234  	case *Return:
   235  		if nsuccs := len(s.block.Succs); nsuccs != 0 {
   236  			s.errorf("Return-terminated block has %d successors; expected none", nsuccs)
   237  			return
   238  		}
   239  		if na, nf := len(instr.Results), s.fn.Signature.Results().Len(); nf != na {
   240  			s.errorf("%d-ary return in %d-ary function", na, nf)
   241  		}
   242  
   243  	case *Panic:
   244  		if nsuccs := len(s.block.Succs); nsuccs != 0 {
   245  			s.errorf("Panic-terminated block has %d successors; expected none", nsuccs)
   246  			return
   247  		}
   248  
   249  	default:
   250  		s.errorf("non-control flow instruction at end of block")
   251  	}
   252  }
   253  
   254  func (s *sanity) checkBlock(b *BasicBlock, index int) {
   255  	s.block = b
   256  
   257  	if b.Index != index {
   258  		s.errorf("block has incorrect Index %d", b.Index)
   259  	}
   260  	if b.parent != s.fn {
   261  		s.errorf("block has incorrect parent %s", b.parent)
   262  	}
   263  
   264  	// Check all blocks are reachable.
   265  	// (The entry block is always implicitly reachable,
   266  	// as is the Recover block, if any.)
   267  	if (index > 0 && b != b.parent.Recover) && len(b.Preds) == 0 {
   268  		s.warnf("unreachable block")
   269  		if b.Instrs == nil {
   270  			// Since this block is about to be pruned,
   271  			// tolerating transient problems in it
   272  			// simplifies other optimizations.
   273  			return
   274  		}
   275  	}
   276  
   277  	// Check predecessor and successor relations are dual,
   278  	// and that all blocks in CFG belong to same function.
   279  	for _, a := range b.Preds {
   280  		found := false
   281  		for _, bb := range a.Succs {
   282  			if bb == b {
   283  				found = true
   284  				break
   285  			}
   286  		}
   287  		if !found {
   288  			s.errorf("expected successor edge in predecessor %s; found only: %s", a, a.Succs)
   289  		}
   290  		if a.parent != s.fn {
   291  			s.errorf("predecessor %s belongs to different function %s", a, a.parent)
   292  		}
   293  	}
   294  	for _, c := range b.Succs {
   295  		found := false
   296  		for _, bb := range c.Preds {
   297  			if bb == b {
   298  				found = true
   299  				break
   300  			}
   301  		}
   302  		if !found {
   303  			s.errorf("expected predecessor edge in successor %s; found only: %s", c, c.Preds)
   304  		}
   305  		if c.parent != s.fn {
   306  			s.errorf("successor %s belongs to different function %s", c, c.parent)
   307  		}
   308  	}
   309  
   310  	// Check each instruction is sane.
   311  	n := len(b.Instrs)
   312  	if n == 0 {
   313  		s.errorf("basic block contains no instructions")
   314  	}
   315  	var rands [10]*Value // reuse storage
   316  	for j, instr := range b.Instrs {
   317  		if instr == nil {
   318  			s.errorf("nil instruction at index %d", j)
   319  			continue
   320  		}
   321  		if b2 := instr.Block(); b2 == nil {
   322  			s.errorf("nil Block() for instruction at index %d", j)
   323  			continue
   324  		} else if b2 != b {
   325  			s.errorf("wrong Block() (%s) for instruction at index %d ", b2, j)
   326  			continue
   327  		}
   328  		if j < n-1 {
   329  			s.checkInstr(j, instr)
   330  		} else {
   331  			s.checkFinalInstr(j, instr)
   332  		}
   333  
   334  		// Check Instruction.Operands.
   335  	operands:
   336  		for i, op := range instr.Operands(rands[:0]) {
   337  			if op == nil {
   338  				s.errorf("nil operand pointer %d of %s", i, instr)
   339  				continue
   340  			}
   341  			val := *op
   342  			if val == nil {
   343  				continue // a nil operand is ok
   344  			}
   345  
   346  			// Check that "untyped" types only appear on constant operands.
   347  			if _, ok := (*op).(*Const); !ok {
   348  				if basic, ok := (*op).Type().(*types.Basic); ok {
   349  					if basic.Info()&types.IsUntyped != 0 {
   350  						s.errorf("operand #%d of %s is untyped: %s", i, instr, basic)
   351  					}
   352  				}
   353  			}
   354  
   355  			// Check that Operands that are also Instructions belong to same function.
   356  			// TODO(adonovan): also check their block dominates block b.
   357  			if val, ok := val.(Instruction); ok {
   358  				if val.Parent() != s.fn {
   359  					s.errorf("operand %d of %s is an instruction (%s) from function %s", i, instr, val, val.Parent())
   360  				}
   361  			}
   362  
   363  			// Check that each function-local operand of
   364  			// instr refers back to instr.  (NB: quadratic)
   365  			switch val := val.(type) {
   366  			case *Const, *Global, *Builtin:
   367  				continue // not local
   368  			case *Function:
   369  				if val.parent == nil {
   370  					continue // only anon functions are local
   371  				}
   372  			}
   373  
   374  			// TODO(adonovan): check val.Parent() != nil <=> val.Referrers() is defined.
   375  
   376  			if refs := val.Referrers(); refs != nil {
   377  				for _, ref := range *refs {
   378  					if ref == instr {
   379  						continue operands
   380  					}
   381  				}
   382  				s.errorf("operand %d of %s (%s) does not refer to us", i, instr, val)
   383  			} else {
   384  				s.errorf("operand %d of %s (%s) has no referrers", i, instr, val)
   385  			}
   386  		}
   387  	}
   388  }
   389  
   390  func (s *sanity) checkReferrerList(v Value) {
   391  	refs := v.Referrers()
   392  	if refs == nil {
   393  		s.errorf("%s has missing referrer list", v.Name())
   394  		return
   395  	}
   396  	for i, ref := range *refs {
   397  		if _, ok := s.instrs[ref]; !ok {
   398  			s.errorf("%s.Referrers()[%d] = %s is not an instruction belonging to this function", v.Name(), i, ref)
   399  		}
   400  	}
   401  }
   402  
   403  func (s *sanity) checkFunction(fn *Function) bool {
   404  	// TODO(adonovan): check Function invariants:
   405  	// - check params match signature
   406  	// - check transient fields are nil
   407  	// - warn if any fn.Locals do not appear among block instructions.
   408  	s.fn = fn
   409  	if fn.Prog == nil {
   410  		s.errorf("nil Prog")
   411  	}
   412  
   413  	fn.String()            // must not crash
   414  	fn.RelString(fn.pkg()) // must not crash
   415  
   416  	// All functions have a package, except delegates (which are
   417  	// shared across packages, or duplicated as weak symbols in a
   418  	// separate-compilation model), and error.Error.
   419  	if fn.Pkg == nil {
   420  		if strings.HasPrefix(fn.Synthetic, "wrapper ") ||
   421  			strings.HasPrefix(fn.Synthetic, "bound ") ||
   422  			strings.HasPrefix(fn.Synthetic, "thunk ") ||
   423  			strings.HasSuffix(fn.name, "Error") {
   424  			// ok
   425  		} else {
   426  			s.errorf("nil Pkg")
   427  		}
   428  	}
   429  	if src, syn := fn.Synthetic == "", fn.Syntax() != nil; src != syn {
   430  		s.errorf("got fromSource=%t, hasSyntax=%t; want same values", src, syn)
   431  	}
   432  	for i, l := range fn.Locals {
   433  		if l.Parent() != fn {
   434  			s.errorf("Local %s at index %d has wrong parent", l.Name(), i)
   435  		}
   436  		if l.Heap {
   437  			s.errorf("Local %s at index %d has Heap flag set", l.Name(), i)
   438  		}
   439  	}
   440  	// Build the set of valid referrers.
   441  	s.instrs = make(map[Instruction]struct{})
   442  	for _, b := range fn.Blocks {
   443  		for _, instr := range b.Instrs {
   444  			s.instrs[instr] = struct{}{}
   445  		}
   446  	}
   447  	for i, p := range fn.Params {
   448  		if p.Parent() != fn {
   449  			s.errorf("Param %s at index %d has wrong parent", p.Name(), i)
   450  		}
   451  		s.checkReferrerList(p)
   452  	}
   453  	for i, fv := range fn.FreeVars {
   454  		if fv.Parent() != fn {
   455  			s.errorf("FreeVar %s at index %d has wrong parent", fv.Name(), i)
   456  		}
   457  		s.checkReferrerList(fv)
   458  	}
   459  
   460  	if fn.Blocks != nil && len(fn.Blocks) == 0 {
   461  		// Function _had_ blocks (so it's not external) but
   462  		// they were "optimized" away, even the entry block.
   463  		s.errorf("Blocks slice is non-nil but empty")
   464  	}
   465  	for i, b := range fn.Blocks {
   466  		if b == nil {
   467  			s.warnf("nil *BasicBlock at f.Blocks[%d]", i)
   468  			continue
   469  		}
   470  		s.checkBlock(b, i)
   471  	}
   472  	if fn.Recover != nil && fn.Blocks[fn.Recover.Index] != fn.Recover {
   473  		s.errorf("Recover block is not in Blocks slice")
   474  	}
   475  
   476  	s.block = nil
   477  	for i, anon := range fn.AnonFuncs {
   478  		if anon.Parent() != fn {
   479  			s.errorf("AnonFuncs[%d]=%s but %s.Parent()=%s", i, anon, anon, anon.Parent())
   480  		}
   481  	}
   482  	s.fn = nil
   483  	return !s.insane
   484  }
   485  
   486  // sanityCheckPackage checks invariants of packages upon creation.
   487  // It does not require that the package is built.
   488  // Unlike sanityCheck (for functions), it just panics at the first error.
   489  func sanityCheckPackage(pkg *Package) {
   490  	if pkg.Pkg == nil {
   491  		panic(fmt.Sprintf("Package %s has no Object", pkg))
   492  	}
   493  	pkg.String() // must not crash
   494  
   495  	for name, mem := range pkg.Members {
   496  		if name != mem.Name() {
   497  			panic(fmt.Sprintf("%s: %T.Name() = %s, want %s",
   498  				pkg.Pkg.Path(), mem, mem.Name(), name))
   499  		}
   500  		obj := mem.Object()
   501  		if obj == nil {
   502  			// This check is sound because fields
   503  			// {Global,Function}.object have type
   504  			// types.Object.  (If they were declared as
   505  			// *types.{Var,Func}, we'd have a non-empty
   506  			// interface containing a nil pointer.)
   507  
   508  			continue // not all members have typechecker objects
   509  		}
   510  		if obj.Name() != name {
   511  			if obj.Name() == "init" && strings.HasPrefix(mem.Name(), "init#") {
   512  				// Ok.  The name of a declared init function varies between
   513  				// its types.Func ("init") and its ssa.Function ("init#%d").
   514  			} else {
   515  				panic(fmt.Sprintf("%s: %T.Object().Name() = %s, want %s",
   516  					pkg.Pkg.Path(), mem, obj.Name(), name))
   517  			}
   518  		}
   519  		if obj.Pos() != mem.Pos() {
   520  			panic(fmt.Sprintf("%s Pos=%d obj.Pos=%d", mem, mem.Pos(), obj.Pos()))
   521  		}
   522  	}
   523  }