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