github.com/cockroachdb/tools@v0.0.0-20230222021103-a6d27438930d/go/ssa/ssa.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  package ssa
     6  
     7  // This package defines a high-level intermediate representation for
     8  // Go programs using static single-assignment (SSA) form.
     9  
    10  import (
    11  	"fmt"
    12  	"go/ast"
    13  	"go/constant"
    14  	"go/token"
    15  	"go/types"
    16  	"sync"
    17  
    18  	"golang.org/x/tools/go/types/typeutil"
    19  	"golang.org/x/tools/internal/typeparams"
    20  )
    21  
    22  // A Program is a partial or complete Go program converted to SSA form.
    23  type Program struct {
    24  	Fset       *token.FileSet              // position information for the files of this Program
    25  	imported   map[string]*Package         // all importable Packages, keyed by import path
    26  	packages   map[*types.Package]*Package // all loaded Packages, keyed by object
    27  	mode       BuilderMode                 // set of mode bits for SSA construction
    28  	MethodSets typeutil.MethodSetCache     // cache of type-checker's method-sets
    29  
    30  	canon *canonizer          // type canonicalization map
    31  	ctxt  *typeparams.Context // cache for type checking instantiations
    32  
    33  	methodsMu     sync.Mutex                 // guards the following maps:
    34  	methodSets    typeutil.Map               // maps type to its concrete methodSet
    35  	runtimeTypes  typeutil.Map               // types for which rtypes are needed
    36  	bounds        map[boundsKey]*Function    // bounds for curried x.Method closures
    37  	thunks        map[selectionKey]*Function // thunks for T.Method expressions
    38  	instances     map[*Function]*instanceSet // instances of generic functions
    39  	parameterized tpWalker                   // determines whether a type reaches a type parameter.
    40  }
    41  
    42  // A Package is a single analyzed Go package containing Members for
    43  // all package-level functions, variables, constants and types it
    44  // declares.  These may be accessed directly via Members, or via the
    45  // type-specific accessor methods Func, Type, Var and Const.
    46  //
    47  // Members also contains entries for "init" (the synthetic package
    48  // initializer) and "init#%d", the nth declared init function,
    49  // and unspecified other things too.
    50  type Package struct {
    51  	Prog    *Program                // the owning program
    52  	Pkg     *types.Package          // the corresponding go/types.Package
    53  	Members map[string]Member       // all package members keyed by name (incl. init and init#%d)
    54  	objects map[types.Object]Member // mapping of package objects to members (incl. methods). Contains *NamedConst, *Global, *Function.
    55  	init    *Function               // Func("init"); the package's init function
    56  	debug   bool                    // include full debug info in this package
    57  
    58  	// The following fields are set transiently, then cleared
    59  	// after building.
    60  	buildOnce sync.Once   // ensures package building occurs once
    61  	ninit     int32       // number of init functions
    62  	info      *types.Info // package type information
    63  	files     []*ast.File // package ASTs
    64  	created   creator     // members created as a result of building this package (includes declared functions, wrappers)
    65  }
    66  
    67  // A Member is a member of a Go package, implemented by *NamedConst,
    68  // *Global, *Function, or *Type; they are created by package-level
    69  // const, var, func and type declarations respectively.
    70  type Member interface {
    71  	Name() string                    // declared name of the package member
    72  	String() string                  // package-qualified name of the package member
    73  	RelString(*types.Package) string // like String, but relative refs are unqualified
    74  	Object() types.Object            // typechecker's object for this member, if any
    75  	Pos() token.Pos                  // position of member's declaration, if known
    76  	Type() types.Type                // type of the package member
    77  	Token() token.Token              // token.{VAR,FUNC,CONST,TYPE}
    78  	Package() *Package               // the containing package
    79  }
    80  
    81  // A Type is a Member of a Package representing a package-level named type.
    82  type Type struct {
    83  	object *types.TypeName
    84  	pkg    *Package
    85  }
    86  
    87  // A NamedConst is a Member of a Package representing a package-level
    88  // named constant.
    89  //
    90  // Pos() returns the position of the declaring ast.ValueSpec.Names[*]
    91  // identifier.
    92  //
    93  // NB: a NamedConst is not a Value; it contains a constant Value, which
    94  // it augments with the name and position of its 'const' declaration.
    95  type NamedConst struct {
    96  	object *types.Const
    97  	Value  *Const
    98  	pkg    *Package
    99  }
   100  
   101  // A Value is an SSA value that can be referenced by an instruction.
   102  type Value interface {
   103  	// Name returns the name of this value, and determines how
   104  	// this Value appears when used as an operand of an
   105  	// Instruction.
   106  	//
   107  	// This is the same as the source name for Parameters,
   108  	// Builtins, Functions, FreeVars, Globals.
   109  	// For constants, it is a representation of the constant's value
   110  	// and type.  For all other Values this is the name of the
   111  	// virtual register defined by the instruction.
   112  	//
   113  	// The name of an SSA Value is not semantically significant,
   114  	// and may not even be unique within a function.
   115  	Name() string
   116  
   117  	// If this value is an Instruction, String returns its
   118  	// disassembled form; otherwise it returns unspecified
   119  	// human-readable information about the Value, such as its
   120  	// kind, name and type.
   121  	String() string
   122  
   123  	// Type returns the type of this value.  Many instructions
   124  	// (e.g. IndexAddr) change their behaviour depending on the
   125  	// types of their operands.
   126  	Type() types.Type
   127  
   128  	// Parent returns the function to which this Value belongs.
   129  	// It returns nil for named Functions, Builtin, Const and Global.
   130  	Parent() *Function
   131  
   132  	// Referrers returns the list of instructions that have this
   133  	// value as one of their operands; it may contain duplicates
   134  	// if an instruction has a repeated operand.
   135  	//
   136  	// Referrers actually returns a pointer through which the
   137  	// caller may perform mutations to the object's state.
   138  	//
   139  	// Referrers is currently only defined if Parent()!=nil,
   140  	// i.e. for the function-local values FreeVar, Parameter,
   141  	// Functions (iff anonymous) and all value-defining instructions.
   142  	// It returns nil for named Functions, Builtin, Const and Global.
   143  	//
   144  	// Instruction.Operands contains the inverse of this relation.
   145  	Referrers() *[]Instruction
   146  
   147  	// Pos returns the location of the AST token most closely
   148  	// associated with the operation that gave rise to this value,
   149  	// or token.NoPos if it was not explicit in the source.
   150  	//
   151  	// For each ast.Node type, a particular token is designated as
   152  	// the closest location for the expression, e.g. the Lparen
   153  	// for an *ast.CallExpr.  This permits a compact but
   154  	// approximate mapping from Values to source positions for use
   155  	// in diagnostic messages, for example.
   156  	//
   157  	// (Do not use this position to determine which Value
   158  	// corresponds to an ast.Expr; use Function.ValueForExpr
   159  	// instead.  NB: it requires that the function was built with
   160  	// debug information.)
   161  	Pos() token.Pos
   162  }
   163  
   164  // An Instruction is an SSA instruction that computes a new Value or
   165  // has some effect.
   166  //
   167  // An Instruction that defines a value (e.g. BinOp) also implements
   168  // the Value interface; an Instruction that only has an effect (e.g. Store)
   169  // does not.
   170  type Instruction interface {
   171  	// String returns the disassembled form of this value.
   172  	//
   173  	// Examples of Instructions that are Values:
   174  	//       "x + y"     (BinOp)
   175  	//       "len([])"   (Call)
   176  	// Note that the name of the Value is not printed.
   177  	//
   178  	// Examples of Instructions that are not Values:
   179  	//       "return x"  (Return)
   180  	//       "*y = x"    (Store)
   181  	//
   182  	// (The separation Value.Name() from Value.String() is useful
   183  	// for some analyses which distinguish the operation from the
   184  	// value it defines, e.g., 'y = local int' is both an allocation
   185  	// of memory 'local int' and a definition of a pointer y.)
   186  	String() string
   187  
   188  	// Parent returns the function to which this instruction
   189  	// belongs.
   190  	Parent() *Function
   191  
   192  	// Block returns the basic block to which this instruction
   193  	// belongs.
   194  	Block() *BasicBlock
   195  
   196  	// setBlock sets the basic block to which this instruction belongs.
   197  	setBlock(*BasicBlock)
   198  
   199  	// Operands returns the operands of this instruction: the
   200  	// set of Values it references.
   201  	//
   202  	// Specifically, it appends their addresses to rands, a
   203  	// user-provided slice, and returns the resulting slice,
   204  	// permitting avoidance of memory allocation.
   205  	//
   206  	// The operands are appended in undefined order, but the order
   207  	// is consistent for a given Instruction; the addresses are
   208  	// always non-nil but may point to a nil Value.  Clients may
   209  	// store through the pointers, e.g. to effect a value
   210  	// renaming.
   211  	//
   212  	// Value.Referrers is a subset of the inverse of this
   213  	// relation.  (Referrers are not tracked for all types of
   214  	// Values.)
   215  	Operands(rands []*Value) []*Value
   216  
   217  	// Pos returns the location of the AST token most closely
   218  	// associated with the operation that gave rise to this
   219  	// instruction, or token.NoPos if it was not explicit in the
   220  	// source.
   221  	//
   222  	// For each ast.Node type, a particular token is designated as
   223  	// the closest location for the expression, e.g. the Go token
   224  	// for an *ast.GoStmt.  This permits a compact but approximate
   225  	// mapping from Instructions to source positions for use in
   226  	// diagnostic messages, for example.
   227  	//
   228  	// (Do not use this position to determine which Instruction
   229  	// corresponds to an ast.Expr; see the notes for Value.Pos.
   230  	// This position may be used to determine which non-Value
   231  	// Instruction corresponds to some ast.Stmts, but not all: If
   232  	// and Jump instructions have no Pos(), for example.)
   233  	Pos() token.Pos
   234  }
   235  
   236  // A Node is a node in the SSA value graph.  Every concrete type that
   237  // implements Node is also either a Value, an Instruction, or both.
   238  //
   239  // Node contains the methods common to Value and Instruction, plus the
   240  // Operands and Referrers methods generalized to return nil for
   241  // non-Instructions and non-Values, respectively.
   242  //
   243  // Node is provided to simplify SSA graph algorithms.  Clients should
   244  // use the more specific and informative Value or Instruction
   245  // interfaces where appropriate.
   246  type Node interface {
   247  	// Common methods:
   248  	String() string
   249  	Pos() token.Pos
   250  	Parent() *Function
   251  
   252  	// Partial methods:
   253  	Operands(rands []*Value) []*Value // nil for non-Instructions
   254  	Referrers() *[]Instruction        // nil for non-Values
   255  }
   256  
   257  // Function represents the parameters, results, and code of a function
   258  // or method.
   259  //
   260  // If Blocks is nil, this indicates an external function for which no
   261  // Go source code is available.  In this case, FreeVars and Locals
   262  // are nil too.  Clients performing whole-program analysis must
   263  // handle external functions specially.
   264  //
   265  // Blocks contains the function's control-flow graph (CFG).
   266  // Blocks[0] is the function entry point; block order is not otherwise
   267  // semantically significant, though it may affect the readability of
   268  // the disassembly.
   269  // To iterate over the blocks in dominance order, use DomPreorder().
   270  //
   271  // Recover is an optional second entry point to which control resumes
   272  // after a recovered panic.  The Recover block may contain only a return
   273  // statement, preceded by a load of the function's named return
   274  // parameters, if any.
   275  //
   276  // A nested function (Parent()!=nil) that refers to one or more
   277  // lexically enclosing local variables ("free variables") has FreeVars.
   278  // Such functions cannot be called directly but require a
   279  // value created by MakeClosure which, via its Bindings, supplies
   280  // values for these parameters.
   281  //
   282  // If the function is a method (Signature.Recv() != nil) then the first
   283  // element of Params is the receiver parameter.
   284  //
   285  // A Go package may declare many functions called "init".
   286  // For each one, Object().Name() returns "init" but Name() returns
   287  // "init#1", etc, in declaration order.
   288  //
   289  // Pos() returns the declaring ast.FuncLit.Type.Func or the position
   290  // of the ast.FuncDecl.Name, if the function was explicit in the
   291  // source.  Synthetic wrappers, for which Synthetic != "", may share
   292  // the same position as the function they wrap.
   293  // Syntax.Pos() always returns the position of the declaring "func" token.
   294  //
   295  // Type() returns the function's Signature.
   296  //
   297  // A generic function is a function or method that has uninstantiated type
   298  // parameters (TypeParams() != nil). Consider a hypothetical generic
   299  // method, (*Map[K,V]).Get. It may be instantiated with all ground
   300  // (non-parameterized) types as (*Map[string,int]).Get or with
   301  // parameterized types as (*Map[string,U]).Get, where U is a type parameter.
   302  // In both instantiations, Origin() refers to the instantiated generic
   303  // method, (*Map[K,V]).Get, TypeParams() refers to the parameters [K,V] of
   304  // the generic method. TypeArgs() refers to [string,U] or [string,int],
   305  // respectively, and is nil in the generic method.
   306  type Function struct {
   307  	name      string
   308  	object    types.Object // a declared *types.Func or one of its wrappers
   309  	method    *selection   // info about provenance of synthetic methods; thunk => non-nil
   310  	Signature *types.Signature
   311  	pos       token.Pos
   312  
   313  	Synthetic string        // provenance of synthetic function; "" for true source functions
   314  	syntax    ast.Node      // *ast.Func{Decl,Lit}; replaced with simple ast.Node after build, unless debug mode
   315  	parent    *Function     // enclosing function if anon; nil if global
   316  	Pkg       *Package      // enclosing package; nil for shared funcs (wrappers and error.Error)
   317  	Prog      *Program      // enclosing program
   318  	Params    []*Parameter  // function parameters; for methods, includes receiver
   319  	FreeVars  []*FreeVar    // free variables whose values must be supplied by closure
   320  	Locals    []*Alloc      // local variables of this function
   321  	Blocks    []*BasicBlock // basic blocks of the function; nil => external
   322  	Recover   *BasicBlock   // optional; control transfers here after recovered panic
   323  	AnonFuncs []*Function   // anonymous functions directly beneath this one
   324  	referrers []Instruction // referring instructions (iff Parent() != nil)
   325  	built     bool          // function has completed both CREATE and BUILD phase.
   326  	anonIdx   int32         // position of a nested function in parent's AnonFuncs. fn.Parent()!=nil => fn.Parent().AnonFunc[fn.anonIdx] == fn.
   327  
   328  	typeparams     *typeparams.TypeParamList // type parameters of this function. typeparams.Len() > 0 => generic or instance of generic function
   329  	typeargs       []types.Type              // type arguments that instantiated typeparams. len(typeargs) > 0 => instance of generic function
   330  	topLevelOrigin *Function                 // the origin function if this is an instance of a source function. nil if Parent()!=nil.
   331  
   332  	// The following fields are set transiently during building,
   333  	// then cleared.
   334  	currentBlock *BasicBlock              // where to emit code
   335  	objects      map[types.Object]Value   // addresses of local variables
   336  	namedResults []*Alloc                 // tuple of named results
   337  	targets      *targets                 // linked stack of branch targets
   338  	lblocks      map[types.Object]*lblock // labelled blocks
   339  	info         *types.Info              // *types.Info to build from. nil for wrappers.
   340  	subst        *subster                 // non-nil => expand generic body using this type substitution of ground types
   341  }
   342  
   343  // BasicBlock represents an SSA basic block.
   344  //
   345  // The final element of Instrs is always an explicit transfer of
   346  // control (If, Jump, Return, or Panic).
   347  //
   348  // A block may contain no Instructions only if it is unreachable,
   349  // i.e., Preds is nil.  Empty blocks are typically pruned.
   350  //
   351  // BasicBlocks and their Preds/Succs relation form a (possibly cyclic)
   352  // graph independent of the SSA Value graph: the control-flow graph or
   353  // CFG.  It is illegal for multiple edges to exist between the same
   354  // pair of blocks.
   355  //
   356  // Each BasicBlock is also a node in the dominator tree of the CFG.
   357  // The tree may be navigated using Idom()/Dominees() and queried using
   358  // Dominates().
   359  //
   360  // The order of Preds and Succs is significant (to Phi and If
   361  // instructions, respectively).
   362  type BasicBlock struct {
   363  	Index        int            // index of this block within Parent().Blocks
   364  	Comment      string         // optional label; no semantic significance
   365  	parent       *Function      // parent function
   366  	Instrs       []Instruction  // instructions in order
   367  	Preds, Succs []*BasicBlock  // predecessors and successors
   368  	succs2       [2]*BasicBlock // initial space for Succs
   369  	dom          domInfo        // dominator tree info
   370  	gaps         int            // number of nil Instrs (transient)
   371  	rundefers    int            // number of rundefers (transient)
   372  }
   373  
   374  // Pure values ----------------------------------------
   375  
   376  // A FreeVar represents a free variable of the function to which it
   377  // belongs.
   378  //
   379  // FreeVars are used to implement anonymous functions, whose free
   380  // variables are lexically captured in a closure formed by
   381  // MakeClosure.  The value of such a free var is an Alloc or another
   382  // FreeVar and is considered a potentially escaping heap address, with
   383  // pointer type.
   384  //
   385  // FreeVars are also used to implement bound method closures.  Such a
   386  // free var represents the receiver value and may be of any type that
   387  // has concrete methods.
   388  //
   389  // Pos() returns the position of the value that was captured, which
   390  // belongs to an enclosing function.
   391  type FreeVar struct {
   392  	name      string
   393  	typ       types.Type
   394  	pos       token.Pos
   395  	parent    *Function
   396  	referrers []Instruction
   397  
   398  	// Transiently needed during building.
   399  	outer Value // the Value captured from the enclosing context.
   400  }
   401  
   402  // A Parameter represents an input parameter of a function.
   403  type Parameter struct {
   404  	name      string
   405  	object    types.Object // a *types.Var; nil for non-source locals
   406  	typ       types.Type
   407  	pos       token.Pos
   408  	parent    *Function
   409  	referrers []Instruction
   410  }
   411  
   412  // A Const represents a value known at build time.
   413  //
   414  // Consts include true constants of boolean, numeric, and string types, as
   415  // defined by the Go spec; these are represented by a non-nil Value field.
   416  //
   417  // Consts also include the "zero" value of any type, of which the nil values
   418  // of various pointer-like types are a special case; these are represented
   419  // by a nil Value field.
   420  //
   421  // Pos() returns token.NoPos.
   422  //
   423  // Example printed forms:
   424  //
   425  //		42:int
   426  //		"hello":untyped string
   427  //		3+4i:MyComplex
   428  //		nil:*int
   429  //		nil:[]string
   430  //		[3]int{}:[3]int
   431  //		struct{x string}{}:struct{x string}
   432  //	    0:interface{int|int64}
   433  //	    nil:interface{bool|int} // no go/constant representation
   434  type Const struct {
   435  	typ   types.Type
   436  	Value constant.Value
   437  }
   438  
   439  // A Global is a named Value holding the address of a package-level
   440  // variable.
   441  //
   442  // Pos() returns the position of the ast.ValueSpec.Names[*]
   443  // identifier.
   444  type Global struct {
   445  	name   string
   446  	object types.Object // a *types.Var; may be nil for synthetics e.g. init$guard
   447  	typ    types.Type
   448  	pos    token.Pos
   449  
   450  	Pkg *Package
   451  }
   452  
   453  // A Builtin represents a specific use of a built-in function, e.g. len.
   454  //
   455  // Builtins are immutable values.  Builtins do not have addresses.
   456  // Builtins can only appear in CallCommon.Value.
   457  //
   458  // Name() indicates the function: one of the built-in functions from the
   459  // Go spec (excluding "make" and "new") or one of these ssa-defined
   460  // intrinsics:
   461  //
   462  //	// wrapnilchk returns ptr if non-nil, panics otherwise.
   463  //	// (For use in indirection wrappers.)
   464  //	func ssa:wrapnilchk(ptr *T, recvType, methodName string) *T
   465  //
   466  // Object() returns a *types.Builtin for built-ins defined by the spec,
   467  // nil for others.
   468  //
   469  // Type() returns a *types.Signature representing the effective
   470  // signature of the built-in for this call.
   471  type Builtin struct {
   472  	name string
   473  	sig  *types.Signature
   474  }
   475  
   476  // Value-defining instructions  ----------------------------------------
   477  
   478  // The Alloc instruction reserves space for a variable of the given type,
   479  // zero-initializes it, and yields its address.
   480  //
   481  // Alloc values are always addresses, and have pointer types, so the
   482  // type of the allocated variable is actually
   483  // Type().Underlying().(*types.Pointer).Elem().
   484  //
   485  // If Heap is false, Alloc allocates space in the function's
   486  // activation record (frame); we refer to an Alloc(Heap=false) as a
   487  // "local" alloc.  Each local Alloc returns the same address each time
   488  // it is executed within the same activation; the space is
   489  // re-initialized to zero.
   490  //
   491  // If Heap is true, Alloc allocates space in the heap; we
   492  // refer to an Alloc(Heap=true) as a "new" alloc.  Each new Alloc
   493  // returns a different address each time it is executed.
   494  //
   495  // When Alloc is applied to a channel, map or slice type, it returns
   496  // the address of an uninitialized (nil) reference of that kind; store
   497  // the result of MakeSlice, MakeMap or MakeChan in that location to
   498  // instantiate these types.
   499  //
   500  // Pos() returns the ast.CompositeLit.Lbrace for a composite literal,
   501  // or the ast.CallExpr.Rparen for a call to new() or for a call that
   502  // allocates a varargs slice.
   503  //
   504  // Example printed form:
   505  //
   506  //	t0 = local int
   507  //	t1 = new int
   508  type Alloc struct {
   509  	register
   510  	Comment string
   511  	Heap    bool
   512  	index   int // dense numbering; for lifting
   513  }
   514  
   515  // The Phi instruction represents an SSA φ-node, which combines values
   516  // that differ across incoming control-flow edges and yields a new
   517  // value.  Within a block, all φ-nodes must appear before all non-φ
   518  // nodes.
   519  //
   520  // Pos() returns the position of the && or || for short-circuit
   521  // control-flow joins, or that of the *Alloc for φ-nodes inserted
   522  // during SSA renaming.
   523  //
   524  // Example printed form:
   525  //
   526  //	t2 = phi [0: t0, 1: t1]
   527  type Phi struct {
   528  	register
   529  	Comment string  // a hint as to its purpose
   530  	Edges   []Value // Edges[i] is value for Block().Preds[i]
   531  }
   532  
   533  // The Call instruction represents a function or method call.
   534  //
   535  // The Call instruction yields the function result if there is exactly
   536  // one.  Otherwise it returns a tuple, the components of which are
   537  // accessed via Extract.
   538  //
   539  // See CallCommon for generic function call documentation.
   540  //
   541  // Pos() returns the ast.CallExpr.Lparen, if explicit in the source.
   542  //
   543  // Example printed form:
   544  //
   545  //	t2 = println(t0, t1)
   546  //	t4 = t3()
   547  //	t7 = invoke t5.Println(...t6)
   548  type Call struct {
   549  	register
   550  	Call CallCommon
   551  }
   552  
   553  // The BinOp instruction yields the result of binary operation X Op Y.
   554  //
   555  // Pos() returns the ast.BinaryExpr.OpPos, if explicit in the source.
   556  //
   557  // Example printed form:
   558  //
   559  //	t1 = t0 + 1:int
   560  type BinOp struct {
   561  	register
   562  	// One of:
   563  	// ADD SUB MUL QUO REM          + - * / %
   564  	// AND OR XOR SHL SHR AND_NOT   & | ^ << >> &^
   565  	// EQL NEQ LSS LEQ GTR GEQ      == != < <= < >=
   566  	Op   token.Token
   567  	X, Y Value
   568  }
   569  
   570  // The UnOp instruction yields the result of Op X.
   571  // ARROW is channel receive.
   572  // MUL is pointer indirection (load).
   573  // XOR is bitwise complement.
   574  // SUB is negation.
   575  // NOT is logical negation.
   576  //
   577  // If CommaOk and Op=ARROW, the result is a 2-tuple of the value above
   578  // and a boolean indicating the success of the receive.  The
   579  // components of the tuple are accessed using Extract.
   580  //
   581  // Pos() returns the ast.UnaryExpr.OpPos, if explicit in the source.
   582  // For receive operations (ARROW) implicit in ranging over a channel,
   583  // Pos() returns the ast.RangeStmt.For.
   584  // For implicit memory loads (STAR), Pos() returns the position of the
   585  // most closely associated source-level construct; the details are not
   586  // specified.
   587  //
   588  // Example printed form:
   589  //
   590  //	t0 = *x
   591  //	t2 = <-t1,ok
   592  type UnOp struct {
   593  	register
   594  	Op      token.Token // One of: NOT SUB ARROW MUL XOR ! - <- * ^
   595  	X       Value
   596  	CommaOk bool
   597  }
   598  
   599  // The ChangeType instruction applies to X a value-preserving type
   600  // change to Type().
   601  //
   602  // Type changes are permitted:
   603  //   - between a named type and its underlying type.
   604  //   - between two named types of the same underlying type.
   605  //   - between (possibly named) pointers to identical base types.
   606  //   - from a bidirectional channel to a read- or write-channel,
   607  //     optionally adding/removing a name.
   608  //   - between a type (t) and an instance of the type (tσ), i.e.
   609  //     Type() == σ(X.Type()) (or X.Type()== σ(Type())) where
   610  //     σ is the type substitution of Parent().TypeParams by
   611  //     Parent().TypeArgs.
   612  //
   613  // This operation cannot fail dynamically.
   614  //
   615  // Type changes may to be to or from a type parameter (or both). All
   616  // types in the type set of X.Type() have a value-preserving type
   617  // change to all types in the type set of Type().
   618  //
   619  // Pos() returns the ast.CallExpr.Lparen, if the instruction arose
   620  // from an explicit conversion in the source.
   621  //
   622  // Example printed form:
   623  //
   624  //	t1 = changetype *int <- IntPtr (t0)
   625  type ChangeType struct {
   626  	register
   627  	X Value
   628  }
   629  
   630  // The Convert instruction yields the conversion of value X to type
   631  // Type().  One or both of those types is basic (but possibly named).
   632  //
   633  // A conversion may change the value and representation of its operand.
   634  // Conversions are permitted:
   635  //   - between real numeric types.
   636  //   - between complex numeric types.
   637  //   - between string and []byte or []rune.
   638  //   - between pointers and unsafe.Pointer.
   639  //   - between unsafe.Pointer and uintptr.
   640  //   - from (Unicode) integer to (UTF-8) string.
   641  //
   642  // A conversion may imply a type name change also.
   643  //
   644  // Conversions may to be to or from a type parameter. All types in
   645  // the type set of X.Type() can be converted to all types in the type
   646  // set of Type().
   647  //
   648  // This operation cannot fail dynamically.
   649  //
   650  // Conversions of untyped string/number/bool constants to a specific
   651  // representation are eliminated during SSA construction.
   652  //
   653  // Pos() returns the ast.CallExpr.Lparen, if the instruction arose
   654  // from an explicit conversion in the source.
   655  //
   656  // Example printed form:
   657  //
   658  //	t1 = convert []byte <- string (t0)
   659  type Convert struct {
   660  	register
   661  	X Value
   662  }
   663  
   664  // The MultiConvert instruction yields the conversion of value X to type
   665  // Type(). Either X.Type() or Type() must be a type parameter. Each
   666  // type in the type set of X.Type() can be converted to each type in the
   667  // type set of Type().
   668  //
   669  // See the documentation for Convert, ChangeType, and SliceToArrayPointer
   670  // for the conversions that are permitted. Additionally conversions of
   671  // slices to arrays are permitted.
   672  //
   673  // This operation can fail dynamically (see SliceToArrayPointer).
   674  //
   675  // Pos() returns the ast.CallExpr.Lparen, if the instruction arose
   676  // from an explicit conversion in the source.
   677  //
   678  // Example printed form:
   679  //
   680  //	t1 = multiconvert D <- S (t0) [*[2]rune <- []rune | string <- []rune]
   681  type MultiConvert struct {
   682  	register
   683  	X    Value
   684  	from []*typeparams.Term
   685  	to   []*typeparams.Term
   686  }
   687  
   688  // ChangeInterface constructs a value of one interface type from a
   689  // value of another interface type known to be assignable to it.
   690  // This operation cannot fail.
   691  //
   692  // Pos() returns the ast.CallExpr.Lparen if the instruction arose from
   693  // an explicit T(e) conversion; the ast.TypeAssertExpr.Lparen if the
   694  // instruction arose from an explicit e.(T) operation; or token.NoPos
   695  // otherwise.
   696  //
   697  // Example printed form:
   698  //
   699  //	t1 = change interface interface{} <- I (t0)
   700  type ChangeInterface struct {
   701  	register
   702  	X Value
   703  }
   704  
   705  // The SliceToArrayPointer instruction yields the conversion of slice X to
   706  // array pointer.
   707  //
   708  // Pos() returns the ast.CallExpr.Lparen, if the instruction arose
   709  // from an explicit conversion in the source.
   710  //
   711  // Conversion may to be to or from a type parameter. All types in
   712  // the type set of X.Type() must be a slice types that can be converted to
   713  // all types in the type set of Type() which must all be pointer to array
   714  // types.
   715  //
   716  // This operation can fail dynamically if the length of the slice is less
   717  // than the length of the array.
   718  //
   719  // Example printed form:
   720  //
   721  //	t1 = slice to array pointer *[4]byte <- []byte (t0)
   722  type SliceToArrayPointer struct {
   723  	register
   724  	X Value
   725  }
   726  
   727  // MakeInterface constructs an instance of an interface type from a
   728  // value of a concrete type.
   729  //
   730  // Use Program.MethodSets.MethodSet(X.Type()) to find the method-set
   731  // of X, and Program.MethodValue(m) to find the implementation of a method.
   732  //
   733  // To construct the zero value of an interface type T, use:
   734  //
   735  //	NewConst(constant.MakeNil(), T, pos)
   736  //
   737  // Pos() returns the ast.CallExpr.Lparen, if the instruction arose
   738  // from an explicit conversion in the source.
   739  //
   740  // Example printed form:
   741  //
   742  //	t1 = make interface{} <- int (42:int)
   743  //	t2 = make Stringer <- t0
   744  type MakeInterface struct {
   745  	register
   746  	X Value
   747  }
   748  
   749  // The MakeClosure instruction yields a closure value whose code is
   750  // Fn and whose free variables' values are supplied by Bindings.
   751  //
   752  // Type() returns a (possibly named) *types.Signature.
   753  //
   754  // Pos() returns the ast.FuncLit.Type.Func for a function literal
   755  // closure or the ast.SelectorExpr.Sel for a bound method closure.
   756  //
   757  // Example printed form:
   758  //
   759  //	t0 = make closure anon@1.2 [x y z]
   760  //	t1 = make closure bound$(main.I).add [i]
   761  type MakeClosure struct {
   762  	register
   763  	Fn       Value   // always a *Function
   764  	Bindings []Value // values for each free variable in Fn.FreeVars
   765  }
   766  
   767  // The MakeMap instruction creates a new hash-table-based map object
   768  // and yields a value of kind map.
   769  //
   770  // Type() returns a (possibly named) *types.Map.
   771  //
   772  // Pos() returns the ast.CallExpr.Lparen, if created by make(map), or
   773  // the ast.CompositeLit.Lbrack if created by a literal.
   774  //
   775  // Example printed form:
   776  //
   777  //	t1 = make map[string]int t0
   778  //	t1 = make StringIntMap t0
   779  type MakeMap struct {
   780  	register
   781  	Reserve Value // initial space reservation; nil => default
   782  }
   783  
   784  // The MakeChan instruction creates a new channel object and yields a
   785  // value of kind chan.
   786  //
   787  // Type() returns a (possibly named) *types.Chan.
   788  //
   789  // Pos() returns the ast.CallExpr.Lparen for the make(chan) that
   790  // created it.
   791  //
   792  // Example printed form:
   793  //
   794  //	t0 = make chan int 0
   795  //	t0 = make IntChan 0
   796  type MakeChan struct {
   797  	register
   798  	Size Value // int; size of buffer; zero => synchronous.
   799  }
   800  
   801  // The MakeSlice instruction yields a slice of length Len backed by a
   802  // newly allocated array of length Cap.
   803  //
   804  // Both Len and Cap must be non-nil Values of integer type.
   805  //
   806  // (Alloc(types.Array) followed by Slice will not suffice because
   807  // Alloc can only create arrays of constant length.)
   808  //
   809  // Type() returns a (possibly named) *types.Slice.
   810  //
   811  // Pos() returns the ast.CallExpr.Lparen for the make([]T) that
   812  // created it.
   813  //
   814  // Example printed form:
   815  //
   816  //	t1 = make []string 1:int t0
   817  //	t1 = make StringSlice 1:int t0
   818  type MakeSlice struct {
   819  	register
   820  	Len Value
   821  	Cap Value
   822  }
   823  
   824  // The Slice instruction yields a slice of an existing string, slice
   825  // or *array X between optional integer bounds Low and High.
   826  //
   827  // Dynamically, this instruction panics if X evaluates to a nil *array
   828  // pointer.
   829  //
   830  // Type() returns string if the type of X was string, otherwise a
   831  // *types.Slice with the same element type as X.
   832  //
   833  // Pos() returns the ast.SliceExpr.Lbrack if created by a x[:] slice
   834  // operation, the ast.CompositeLit.Lbrace if created by a literal, or
   835  // NoPos if not explicit in the source (e.g. a variadic argument slice).
   836  //
   837  // Example printed form:
   838  //
   839  //	t1 = slice t0[1:]
   840  type Slice struct {
   841  	register
   842  	X              Value // slice, string, or *array
   843  	Low, High, Max Value // each may be nil
   844  }
   845  
   846  // The FieldAddr instruction yields the address of Field of *struct X.
   847  //
   848  // The field is identified by its index within the field list of the
   849  // struct type of X.
   850  //
   851  // Dynamically, this instruction panics if X evaluates to a nil
   852  // pointer.
   853  //
   854  // Type() returns a (possibly named) *types.Pointer.
   855  //
   856  // Pos() returns the position of the ast.SelectorExpr.Sel for the
   857  // field, if explicit in the source. For implicit selections, returns
   858  // the position of the inducing explicit selection. If produced for a
   859  // struct literal S{f: e}, it returns the position of the colon; for
   860  // S{e} it returns the start of expression e.
   861  //
   862  // Example printed form:
   863  //
   864  //	t1 = &t0.name [#1]
   865  type FieldAddr struct {
   866  	register
   867  	X     Value // *struct
   868  	Field int   // field is typeparams.CoreType(X.Type().Underlying().(*types.Pointer).Elem()).(*types.Struct).Field(Field)
   869  }
   870  
   871  // The Field instruction yields the Field of struct X.
   872  //
   873  // The field is identified by its index within the field list of the
   874  // struct type of X; by using numeric indices we avoid ambiguity of
   875  // package-local identifiers and permit compact representations.
   876  //
   877  // Pos() returns the position of the ast.SelectorExpr.Sel for the
   878  // field, if explicit in the source. For implicit selections, returns
   879  // the position of the inducing explicit selection.
   880  
   881  // Example printed form:
   882  //
   883  //	t1 = t0.name [#1]
   884  type Field struct {
   885  	register
   886  	X     Value // struct
   887  	Field int   // index into typeparams.CoreType(X.Type()).(*types.Struct).Fields
   888  }
   889  
   890  // The IndexAddr instruction yields the address of the element at
   891  // index Index of collection X.  Index is an integer expression.
   892  //
   893  // The elements of maps and strings are not addressable; use Lookup (map),
   894  // Index (string), or MapUpdate instead.
   895  //
   896  // Dynamically, this instruction panics if X evaluates to a nil *array
   897  // pointer.
   898  //
   899  // Type() returns a (possibly named) *types.Pointer.
   900  //
   901  // Pos() returns the ast.IndexExpr.Lbrack for the index operation, if
   902  // explicit in the source.
   903  //
   904  // Example printed form:
   905  //
   906  //	t2 = &t0[t1]
   907  type IndexAddr struct {
   908  	register
   909  	X     Value // *array, slice or type parameter with types array, *array, or slice.
   910  	Index Value // numeric index
   911  }
   912  
   913  // The Index instruction yields element Index of collection X, an array,
   914  // string or type parameter containing an array, a string, a pointer to an,
   915  // array or a slice.
   916  //
   917  // Pos() returns the ast.IndexExpr.Lbrack for the index operation, if
   918  // explicit in the source.
   919  //
   920  // Example printed form:
   921  //
   922  //	t2 = t0[t1]
   923  type Index struct {
   924  	register
   925  	X     Value // array, string or type parameter with types array, *array, slice, or string.
   926  	Index Value // integer index
   927  }
   928  
   929  // The Lookup instruction yields element Index of collection map X.
   930  // Index is the appropriate key type.
   931  //
   932  // If CommaOk, the result is a 2-tuple of the value above and a
   933  // boolean indicating the result of a map membership test for the key.
   934  // The components of the tuple are accessed using Extract.
   935  //
   936  // Pos() returns the ast.IndexExpr.Lbrack, if explicit in the source.
   937  //
   938  // Example printed form:
   939  //
   940  //	t2 = t0[t1]
   941  //	t5 = t3[t4],ok
   942  type Lookup struct {
   943  	register
   944  	X       Value // map
   945  	Index   Value // key-typed index
   946  	CommaOk bool  // return a value,ok pair
   947  }
   948  
   949  // SelectState is a helper for Select.
   950  // It represents one goal state and its corresponding communication.
   951  type SelectState struct {
   952  	Dir       types.ChanDir // direction of case (SendOnly or RecvOnly)
   953  	Chan      Value         // channel to use (for send or receive)
   954  	Send      Value         // value to send (for send)
   955  	Pos       token.Pos     // position of token.ARROW
   956  	DebugNode ast.Node      // ast.SendStmt or ast.UnaryExpr(<-) [debug mode]
   957  }
   958  
   959  // The Select instruction tests whether (or blocks until) one
   960  // of the specified sent or received states is entered.
   961  //
   962  // Let n be the number of States for which Dir==RECV and T_i (0<=i<n)
   963  // be the element type of each such state's Chan.
   964  // Select returns an n+2-tuple
   965  //
   966  //	(index int, recvOk bool, r_0 T_0, ... r_n-1 T_n-1)
   967  //
   968  // The tuple's components, described below, must be accessed via the
   969  // Extract instruction.
   970  //
   971  // If Blocking, select waits until exactly one state holds, i.e. a
   972  // channel becomes ready for the designated operation of sending or
   973  // receiving; select chooses one among the ready states
   974  // pseudorandomly, performs the send or receive operation, and sets
   975  // 'index' to the index of the chosen channel.
   976  //
   977  // If !Blocking, select doesn't block if no states hold; instead it
   978  // returns immediately with index equal to -1.
   979  //
   980  // If the chosen channel was used for a receive, the r_i component is
   981  // set to the received value, where i is the index of that state among
   982  // all n receive states; otherwise r_i has the zero value of type T_i.
   983  // Note that the receive index i is not the same as the state
   984  // index index.
   985  //
   986  // The second component of the triple, recvOk, is a boolean whose value
   987  // is true iff the selected operation was a receive and the receive
   988  // successfully yielded a value.
   989  //
   990  // Pos() returns the ast.SelectStmt.Select.
   991  //
   992  // Example printed form:
   993  //
   994  //	t3 = select nonblocking [<-t0, t1<-t2]
   995  //	t4 = select blocking []
   996  type Select struct {
   997  	register
   998  	States   []*SelectState
   999  	Blocking bool
  1000  }
  1001  
  1002  // The Range instruction yields an iterator over the domain and range
  1003  // of X, which must be a string or map.
  1004  //
  1005  // Elements are accessed via Next.
  1006  //
  1007  // Type() returns an opaque and degenerate "rangeIter" type.
  1008  //
  1009  // Pos() returns the ast.RangeStmt.For.
  1010  //
  1011  // Example printed form:
  1012  //
  1013  //	t0 = range "hello":string
  1014  type Range struct {
  1015  	register
  1016  	X Value // string or map
  1017  }
  1018  
  1019  // The Next instruction reads and advances the (map or string)
  1020  // iterator Iter and returns a 3-tuple value (ok, k, v).  If the
  1021  // iterator is not exhausted, ok is true and k and v are the next
  1022  // elements of the domain and range, respectively.  Otherwise ok is
  1023  // false and k and v are undefined.
  1024  //
  1025  // Components of the tuple are accessed using Extract.
  1026  //
  1027  // The IsString field distinguishes iterators over strings from those
  1028  // over maps, as the Type() alone is insufficient: consider
  1029  // map[int]rune.
  1030  //
  1031  // Type() returns a *types.Tuple for the triple (ok, k, v).
  1032  // The types of k and/or v may be types.Invalid.
  1033  //
  1034  // Example printed form:
  1035  //
  1036  //	t1 = next t0
  1037  type Next struct {
  1038  	register
  1039  	Iter     Value
  1040  	IsString bool // true => string iterator; false => map iterator.
  1041  }
  1042  
  1043  // The TypeAssert instruction tests whether interface value X has type
  1044  // AssertedType.
  1045  //
  1046  // If !CommaOk, on success it returns v, the result of the conversion
  1047  // (defined below); on failure it panics.
  1048  //
  1049  // If CommaOk: on success it returns a pair (v, true) where v is the
  1050  // result of the conversion; on failure it returns (z, false) where z
  1051  // is AssertedType's zero value.  The components of the pair must be
  1052  // accessed using the Extract instruction.
  1053  //
  1054  // If Underlying: tests whether interface value X has the underlying
  1055  // type AssertedType.
  1056  //
  1057  // If AssertedType is a concrete type, TypeAssert checks whether the
  1058  // dynamic type in interface X is equal to it, and if so, the result
  1059  // of the conversion is a copy of the value in the interface.
  1060  //
  1061  // If AssertedType is an interface, TypeAssert checks whether the
  1062  // dynamic type of the interface is assignable to it, and if so, the
  1063  // result of the conversion is a copy of the interface value X.
  1064  // If AssertedType is a superinterface of X.Type(), the operation will
  1065  // fail iff the operand is nil.  (Contrast with ChangeInterface, which
  1066  // performs no nil-check.)
  1067  //
  1068  // Type() reflects the actual type of the result, possibly a
  1069  // 2-types.Tuple; AssertedType is the asserted type.
  1070  //
  1071  // Pos() returns the ast.CallExpr.Lparen if the instruction arose from
  1072  // an explicit T(e) conversion; the ast.TypeAssertExpr.Lparen if the
  1073  // instruction arose from an explicit e.(T) operation; or the
  1074  // ast.CaseClause.Case if the instruction arose from a case of a
  1075  // type-switch statement.
  1076  //
  1077  // Example printed form:
  1078  //
  1079  //	t1 = typeassert t0.(int)
  1080  //	t3 = typeassert,ok t2.(T)
  1081  type TypeAssert struct {
  1082  	register
  1083  	X            Value
  1084  	AssertedType types.Type
  1085  	CommaOk      bool
  1086  }
  1087  
  1088  // The Extract instruction yields component Index of Tuple.
  1089  //
  1090  // This is used to access the results of instructions with multiple
  1091  // return values, such as Call, TypeAssert, Next, UnOp(ARROW) and
  1092  // IndexExpr(Map).
  1093  //
  1094  // Example printed form:
  1095  //
  1096  //	t1 = extract t0 #1
  1097  type Extract struct {
  1098  	register
  1099  	Tuple Value
  1100  	Index int
  1101  }
  1102  
  1103  // Instructions executed for effect.  They do not yield a value. --------------------
  1104  
  1105  // The Jump instruction transfers control to the sole successor of its
  1106  // owning block.
  1107  //
  1108  // A Jump must be the last instruction of its containing BasicBlock.
  1109  //
  1110  // Pos() returns NoPos.
  1111  //
  1112  // Example printed form:
  1113  //
  1114  //	jump done
  1115  type Jump struct {
  1116  	anInstruction
  1117  }
  1118  
  1119  // The If instruction transfers control to one of the two successors
  1120  // of its owning block, depending on the boolean Cond: the first if
  1121  // true, the second if false.
  1122  //
  1123  // An If instruction must be the last instruction of its containing
  1124  // BasicBlock.
  1125  //
  1126  // Pos() returns NoPos.
  1127  //
  1128  // Example printed form:
  1129  //
  1130  //	if t0 goto done else body
  1131  type If struct {
  1132  	anInstruction
  1133  	Cond Value
  1134  }
  1135  
  1136  // The Return instruction returns values and control back to the calling
  1137  // function.
  1138  //
  1139  // len(Results) is always equal to the number of results in the
  1140  // function's signature.
  1141  //
  1142  // If len(Results) > 1, Return returns a tuple value with the specified
  1143  // components which the caller must access using Extract instructions.
  1144  //
  1145  // There is no instruction to return a ready-made tuple like those
  1146  // returned by a "value,ok"-mode TypeAssert, Lookup or UnOp(ARROW) or
  1147  // a tail-call to a function with multiple result parameters.
  1148  //
  1149  // Return must be the last instruction of its containing BasicBlock.
  1150  // Such a block has no successors.
  1151  //
  1152  // Pos() returns the ast.ReturnStmt.Return, if explicit in the source.
  1153  //
  1154  // Example printed form:
  1155  //
  1156  //	return
  1157  //	return nil:I, 2:int
  1158  type Return struct {
  1159  	anInstruction
  1160  	Results []Value
  1161  	pos     token.Pos
  1162  }
  1163  
  1164  // The RunDefers instruction pops and invokes the entire stack of
  1165  // procedure calls pushed by Defer instructions in this function.
  1166  //
  1167  // It is legal to encounter multiple 'rundefers' instructions in a
  1168  // single control-flow path through a function; this is useful in
  1169  // the combined init() function, for example.
  1170  //
  1171  // Pos() returns NoPos.
  1172  //
  1173  // Example printed form:
  1174  //
  1175  //	rundefers
  1176  type RunDefers struct {
  1177  	anInstruction
  1178  }
  1179  
  1180  // The Panic instruction initiates a panic with value X.
  1181  //
  1182  // A Panic instruction must be the last instruction of its containing
  1183  // BasicBlock, which must have no successors.
  1184  //
  1185  // NB: 'go panic(x)' and 'defer panic(x)' do not use this instruction;
  1186  // they are treated as calls to a built-in function.
  1187  //
  1188  // Pos() returns the ast.CallExpr.Lparen if this panic was explicit
  1189  // in the source.
  1190  //
  1191  // Example printed form:
  1192  //
  1193  //	panic t0
  1194  type Panic struct {
  1195  	anInstruction
  1196  	X   Value // an interface{}
  1197  	pos token.Pos
  1198  }
  1199  
  1200  // The Go instruction creates a new goroutine and calls the specified
  1201  // function within it.
  1202  //
  1203  // See CallCommon for generic function call documentation.
  1204  //
  1205  // Pos() returns the ast.GoStmt.Go.
  1206  //
  1207  // Example printed form:
  1208  //
  1209  //	go println(t0, t1)
  1210  //	go t3()
  1211  //	go invoke t5.Println(...t6)
  1212  type Go struct {
  1213  	anInstruction
  1214  	Call CallCommon
  1215  	pos  token.Pos
  1216  }
  1217  
  1218  // The Defer instruction pushes the specified call onto a stack of
  1219  // functions to be called by a RunDefers instruction or by a panic.
  1220  //
  1221  // See CallCommon for generic function call documentation.
  1222  //
  1223  // Pos() returns the ast.DeferStmt.Defer.
  1224  //
  1225  // Example printed form:
  1226  //
  1227  //	defer println(t0, t1)
  1228  //	defer t3()
  1229  //	defer invoke t5.Println(...t6)
  1230  type Defer struct {
  1231  	anInstruction
  1232  	Call CallCommon
  1233  	pos  token.Pos
  1234  }
  1235  
  1236  // The Send instruction sends X on channel Chan.
  1237  //
  1238  // Pos() returns the ast.SendStmt.Arrow, if explicit in the source.
  1239  //
  1240  // Example printed form:
  1241  //
  1242  //	send t0 <- t1
  1243  type Send struct {
  1244  	anInstruction
  1245  	Chan, X Value
  1246  	pos     token.Pos
  1247  }
  1248  
  1249  // The Store instruction stores Val at address Addr.
  1250  // Stores can be of arbitrary types.
  1251  //
  1252  // Pos() returns the position of the source-level construct most closely
  1253  // associated with the memory store operation.
  1254  // Since implicit memory stores are numerous and varied and depend upon
  1255  // implementation choices, the details are not specified.
  1256  //
  1257  // Example printed form:
  1258  //
  1259  //	*x = y
  1260  type Store struct {
  1261  	anInstruction
  1262  	Addr Value
  1263  	Val  Value
  1264  	pos  token.Pos
  1265  }
  1266  
  1267  // The MapUpdate instruction updates the association of Map[Key] to
  1268  // Value.
  1269  //
  1270  // Pos() returns the ast.KeyValueExpr.Colon or ast.IndexExpr.Lbrack,
  1271  // if explicit in the source.
  1272  //
  1273  // Example printed form:
  1274  //
  1275  //	t0[t1] = t2
  1276  type MapUpdate struct {
  1277  	anInstruction
  1278  	Map   Value
  1279  	Key   Value
  1280  	Value Value
  1281  	pos   token.Pos
  1282  }
  1283  
  1284  // A DebugRef instruction maps a source-level expression Expr to the
  1285  // SSA value X that represents the value (!IsAddr) or address (IsAddr)
  1286  // of that expression.
  1287  //
  1288  // DebugRef is a pseudo-instruction: it has no dynamic effect.
  1289  //
  1290  // Pos() returns Expr.Pos(), the start position of the source-level
  1291  // expression.  This is not the same as the "designated" token as
  1292  // documented at Value.Pos(). e.g. CallExpr.Pos() does not return the
  1293  // position of the ("designated") Lparen token.
  1294  //
  1295  // If Expr is an *ast.Ident denoting a var or func, Object() returns
  1296  // the object; though this information can be obtained from the type
  1297  // checker, including it here greatly facilitates debugging.
  1298  // For non-Ident expressions, Object() returns nil.
  1299  //
  1300  // DebugRefs are generated only for functions built with debugging
  1301  // enabled; see Package.SetDebugMode() and the GlobalDebug builder
  1302  // mode flag.
  1303  //
  1304  // DebugRefs are not emitted for ast.Idents referring to constants or
  1305  // predeclared identifiers, since they are trivial and numerous.
  1306  // Nor are they emitted for ast.ParenExprs.
  1307  //
  1308  // (By representing these as instructions, rather than out-of-band,
  1309  // consistency is maintained during transformation passes by the
  1310  // ordinary SSA renaming machinery.)
  1311  //
  1312  // Example printed form:
  1313  //
  1314  //	; *ast.CallExpr @ 102:9 is t5
  1315  //	; var x float64 @ 109:72 is x
  1316  //	; address of *ast.CompositeLit @ 216:10 is t0
  1317  type DebugRef struct {
  1318  	// TODO(generics): Reconsider what DebugRefs are for generics.
  1319  	anInstruction
  1320  	Expr   ast.Expr     // the referring expression (never *ast.ParenExpr)
  1321  	object types.Object // the identity of the source var/func
  1322  	IsAddr bool         // Expr is addressable and X is the address it denotes
  1323  	X      Value        // the value or address of Expr
  1324  }
  1325  
  1326  // Embeddable mix-ins and helpers for common parts of other structs. -----------
  1327  
  1328  // register is a mix-in embedded by all SSA values that are also
  1329  // instructions, i.e. virtual registers, and provides a uniform
  1330  // implementation of most of the Value interface: Value.Name() is a
  1331  // numbered register (e.g. "t0"); the other methods are field accessors.
  1332  //
  1333  // Temporary names are automatically assigned to each register on
  1334  // completion of building a function in SSA form.
  1335  //
  1336  // Clients must not assume that the 'id' value (and the Name() derived
  1337  // from it) is unique within a function.  As always in this API,
  1338  // semantics are determined only by identity; names exist only to
  1339  // facilitate debugging.
  1340  type register struct {
  1341  	anInstruction
  1342  	num       int        // "name" of virtual register, e.g. "t0".  Not guaranteed unique.
  1343  	typ       types.Type // type of virtual register
  1344  	pos       token.Pos  // position of source expression, or NoPos
  1345  	referrers []Instruction
  1346  }
  1347  
  1348  // anInstruction is a mix-in embedded by all Instructions.
  1349  // It provides the implementations of the Block and setBlock methods.
  1350  type anInstruction struct {
  1351  	block *BasicBlock // the basic block of this instruction
  1352  }
  1353  
  1354  // CallCommon is contained by Go, Defer and Call to hold the
  1355  // common parts of a function or method call.
  1356  //
  1357  // Each CallCommon exists in one of two modes, function call and
  1358  // interface method invocation, or "call" and "invoke" for short.
  1359  //
  1360  // 1. "call" mode: when Method is nil (!IsInvoke), a CallCommon
  1361  // represents an ordinary function call of the value in Value,
  1362  // which may be a *Builtin, a *Function or any other value of kind
  1363  // 'func'.
  1364  //
  1365  // Value may be one of:
  1366  //
  1367  //	(a) a *Function, indicating a statically dispatched call
  1368  //	    to a package-level function, an anonymous function, or
  1369  //	    a method of a named type.
  1370  //	(b) a *MakeClosure, indicating an immediately applied
  1371  //	    function literal with free variables.
  1372  //	(c) a *Builtin, indicating a statically dispatched call
  1373  //	    to a built-in function.
  1374  //	(d) any other value, indicating a dynamically dispatched
  1375  //	    function call.
  1376  //
  1377  // StaticCallee returns the identity of the callee in cases
  1378  // (a) and (b), nil otherwise.
  1379  //
  1380  // Args contains the arguments to the call.  If Value is a method,
  1381  // Args[0] contains the receiver parameter.
  1382  //
  1383  // Example printed form:
  1384  //
  1385  //	t2 = println(t0, t1)
  1386  //	go t3()
  1387  //	defer t5(...t6)
  1388  //
  1389  // 2. "invoke" mode: when Method is non-nil (IsInvoke), a CallCommon
  1390  // represents a dynamically dispatched call to an interface method.
  1391  // In this mode, Value is the interface value and Method is the
  1392  // interface's abstract method. The interface value may be a type
  1393  // parameter. Note: an abstract method may be shared by multiple
  1394  // interfaces due to embedding; Value.Type() provides the specific
  1395  // interface used for this call.
  1396  //
  1397  // Value is implicitly supplied to the concrete method implementation
  1398  // as the receiver parameter; in other words, Args[0] holds not the
  1399  // receiver but the first true argument.
  1400  //
  1401  // Example printed form:
  1402  //
  1403  //	t1 = invoke t0.String()
  1404  //	go invoke t3.Run(t2)
  1405  //	defer invoke t4.Handle(...t5)
  1406  //
  1407  // For all calls to variadic functions (Signature().Variadic()),
  1408  // the last element of Args is a slice.
  1409  type CallCommon struct {
  1410  	Value  Value       // receiver (invoke mode) or func value (call mode)
  1411  	Method *types.Func // abstract method (invoke mode)
  1412  	Args   []Value     // actual parameters (in static method call, includes receiver)
  1413  	pos    token.Pos   // position of CallExpr.Lparen, iff explicit in source
  1414  }
  1415  
  1416  // IsInvoke returns true if this call has "invoke" (not "call") mode.
  1417  func (c *CallCommon) IsInvoke() bool {
  1418  	return c.Method != nil
  1419  }
  1420  
  1421  func (c *CallCommon) Pos() token.Pos { return c.pos }
  1422  
  1423  // Signature returns the signature of the called function.
  1424  //
  1425  // For an "invoke"-mode call, the signature of the interface method is
  1426  // returned.
  1427  //
  1428  // In either "call" or "invoke" mode, if the callee is a method, its
  1429  // receiver is represented by sig.Recv, not sig.Params().At(0).
  1430  func (c *CallCommon) Signature() *types.Signature {
  1431  	if c.Method != nil {
  1432  		return c.Method.Type().(*types.Signature)
  1433  	}
  1434  	return typeparams.CoreType(c.Value.Type()).(*types.Signature)
  1435  }
  1436  
  1437  // StaticCallee returns the callee if this is a trivially static
  1438  // "call"-mode call to a function.
  1439  func (c *CallCommon) StaticCallee() *Function {
  1440  	switch fn := c.Value.(type) {
  1441  	case *Function:
  1442  		return fn
  1443  	case *MakeClosure:
  1444  		return fn.Fn.(*Function)
  1445  	}
  1446  	return nil
  1447  }
  1448  
  1449  // Description returns a description of the mode of this call suitable
  1450  // for a user interface, e.g., "static method call".
  1451  func (c *CallCommon) Description() string {
  1452  	switch fn := c.Value.(type) {
  1453  	case *Builtin:
  1454  		return "built-in function call"
  1455  	case *MakeClosure:
  1456  		return "static function closure call"
  1457  	case *Function:
  1458  		if fn.Signature.Recv() != nil {
  1459  			return "static method call"
  1460  		}
  1461  		return "static function call"
  1462  	}
  1463  	if c.IsInvoke() {
  1464  		return "dynamic method call" // ("invoke" mode)
  1465  	}
  1466  	return "dynamic function call"
  1467  }
  1468  
  1469  // The CallInstruction interface, implemented by *Go, *Defer and *Call,
  1470  // exposes the common parts of function-calling instructions,
  1471  // yet provides a way back to the Value defined by *Call alone.
  1472  type CallInstruction interface {
  1473  	Instruction
  1474  	Common() *CallCommon // returns the common parts of the call
  1475  	Value() *Call        // returns the result value of the call (*Call) or nil (*Go, *Defer)
  1476  }
  1477  
  1478  func (s *Call) Common() *CallCommon  { return &s.Call }
  1479  func (s *Defer) Common() *CallCommon { return &s.Call }
  1480  func (s *Go) Common() *CallCommon    { return &s.Call }
  1481  
  1482  func (s *Call) Value() *Call  { return s }
  1483  func (s *Defer) Value() *Call { return nil }
  1484  func (s *Go) Value() *Call    { return nil }
  1485  
  1486  func (v *Builtin) Type() types.Type        { return v.sig }
  1487  func (v *Builtin) Name() string            { return v.name }
  1488  func (*Builtin) Referrers() *[]Instruction { return nil }
  1489  func (v *Builtin) Pos() token.Pos          { return token.NoPos }
  1490  func (v *Builtin) Object() types.Object    { return types.Universe.Lookup(v.name) }
  1491  func (v *Builtin) Parent() *Function       { return nil }
  1492  
  1493  func (v *FreeVar) Type() types.Type          { return v.typ }
  1494  func (v *FreeVar) Name() string              { return v.name }
  1495  func (v *FreeVar) Referrers() *[]Instruction { return &v.referrers }
  1496  func (v *FreeVar) Pos() token.Pos            { return v.pos }
  1497  func (v *FreeVar) Parent() *Function         { return v.parent }
  1498  
  1499  func (v *Global) Type() types.Type                     { return v.typ }
  1500  func (v *Global) Name() string                         { return v.name }
  1501  func (v *Global) Parent() *Function                    { return nil }
  1502  func (v *Global) Pos() token.Pos                       { return v.pos }
  1503  func (v *Global) Referrers() *[]Instruction            { return nil }
  1504  func (v *Global) Token() token.Token                   { return token.VAR }
  1505  func (v *Global) Object() types.Object                 { return v.object }
  1506  func (v *Global) String() string                       { return v.RelString(nil) }
  1507  func (v *Global) Package() *Package                    { return v.Pkg }
  1508  func (v *Global) RelString(from *types.Package) string { return relString(v, from) }
  1509  
  1510  func (v *Function) Name() string         { return v.name }
  1511  func (v *Function) Type() types.Type     { return v.Signature }
  1512  func (v *Function) Pos() token.Pos       { return v.pos }
  1513  func (v *Function) Token() token.Token   { return token.FUNC }
  1514  func (v *Function) Object() types.Object { return v.object }
  1515  func (v *Function) String() string       { return v.RelString(nil) }
  1516  func (v *Function) Package() *Package    { return v.Pkg }
  1517  func (v *Function) Parent() *Function    { return v.parent }
  1518  func (v *Function) Referrers() *[]Instruction {
  1519  	if v.parent != nil {
  1520  		return &v.referrers
  1521  	}
  1522  	return nil
  1523  }
  1524  
  1525  // TypeParams are the function's type parameters if generic or the
  1526  // type parameters that were instantiated if fn is an instantiation.
  1527  //
  1528  // TODO(taking): declare result type as *types.TypeParamList
  1529  // after we drop support for go1.17.
  1530  func (fn *Function) TypeParams() *typeparams.TypeParamList {
  1531  	return fn.typeparams
  1532  }
  1533  
  1534  // TypeArgs are the types that TypeParams() were instantiated by to create fn
  1535  // from fn.Origin().
  1536  func (fn *Function) TypeArgs() []types.Type { return fn.typeargs }
  1537  
  1538  // Origin is the function fn is an instantiation of. Returns nil if fn is not
  1539  // an instantiation.
  1540  func (fn *Function) Origin() *Function {
  1541  	if fn.parent != nil && len(fn.typeargs) > 0 {
  1542  		// Nested functions are BUILT at a different time than there instances.
  1543  		return fn.parent.Origin().AnonFuncs[fn.anonIdx]
  1544  	}
  1545  	return fn.topLevelOrigin
  1546  }
  1547  
  1548  func (v *Parameter) Type() types.Type          { return v.typ }
  1549  func (v *Parameter) Name() string              { return v.name }
  1550  func (v *Parameter) Object() types.Object      { return v.object }
  1551  func (v *Parameter) Referrers() *[]Instruction { return &v.referrers }
  1552  func (v *Parameter) Pos() token.Pos            { return v.pos }
  1553  func (v *Parameter) Parent() *Function         { return v.parent }
  1554  
  1555  func (v *Alloc) Type() types.Type          { return v.typ }
  1556  func (v *Alloc) Referrers() *[]Instruction { return &v.referrers }
  1557  func (v *Alloc) Pos() token.Pos            { return v.pos }
  1558  
  1559  func (v *register) Type() types.Type          { return v.typ }
  1560  func (v *register) setType(typ types.Type)    { v.typ = typ }
  1561  func (v *register) Name() string              { return fmt.Sprintf("t%d", v.num) }
  1562  func (v *register) setNum(num int)            { v.num = num }
  1563  func (v *register) Referrers() *[]Instruction { return &v.referrers }
  1564  func (v *register) Pos() token.Pos            { return v.pos }
  1565  func (v *register) setPos(pos token.Pos)      { v.pos = pos }
  1566  
  1567  func (v *anInstruction) Parent() *Function          { return v.block.parent }
  1568  func (v *anInstruction) Block() *BasicBlock         { return v.block }
  1569  func (v *anInstruction) setBlock(block *BasicBlock) { v.block = block }
  1570  func (v *anInstruction) Referrers() *[]Instruction  { return nil }
  1571  
  1572  func (t *Type) Name() string                         { return t.object.Name() }
  1573  func (t *Type) Pos() token.Pos                       { return t.object.Pos() }
  1574  func (t *Type) Type() types.Type                     { return t.object.Type() }
  1575  func (t *Type) Token() token.Token                   { return token.TYPE }
  1576  func (t *Type) Object() types.Object                 { return t.object }
  1577  func (t *Type) String() string                       { return t.RelString(nil) }
  1578  func (t *Type) Package() *Package                    { return t.pkg }
  1579  func (t *Type) RelString(from *types.Package) string { return relString(t, from) }
  1580  
  1581  func (c *NamedConst) Name() string                         { return c.object.Name() }
  1582  func (c *NamedConst) Pos() token.Pos                       { return c.object.Pos() }
  1583  func (c *NamedConst) String() string                       { return c.RelString(nil) }
  1584  func (c *NamedConst) Type() types.Type                     { return c.object.Type() }
  1585  func (c *NamedConst) Token() token.Token                   { return token.CONST }
  1586  func (c *NamedConst) Object() types.Object                 { return c.object }
  1587  func (c *NamedConst) Package() *Package                    { return c.pkg }
  1588  func (c *NamedConst) RelString(from *types.Package) string { return relString(c, from) }
  1589  
  1590  func (d *DebugRef) Object() types.Object { return d.object }
  1591  
  1592  // Func returns the package-level function of the specified name,
  1593  // or nil if not found.
  1594  func (p *Package) Func(name string) (f *Function) {
  1595  	f, _ = p.Members[name].(*Function)
  1596  	return
  1597  }
  1598  
  1599  // Var returns the package-level variable of the specified name,
  1600  // or nil if not found.
  1601  func (p *Package) Var(name string) (g *Global) {
  1602  	g, _ = p.Members[name].(*Global)
  1603  	return
  1604  }
  1605  
  1606  // Const returns the package-level constant of the specified name,
  1607  // or nil if not found.
  1608  func (p *Package) Const(name string) (c *NamedConst) {
  1609  	c, _ = p.Members[name].(*NamedConst)
  1610  	return
  1611  }
  1612  
  1613  // Type returns the package-level type of the specified name,
  1614  // or nil if not found.
  1615  func (p *Package) Type(name string) (t *Type) {
  1616  	t, _ = p.Members[name].(*Type)
  1617  	return
  1618  }
  1619  
  1620  func (v *Call) Pos() token.Pos      { return v.Call.pos }
  1621  func (s *Defer) Pos() token.Pos     { return s.pos }
  1622  func (s *Go) Pos() token.Pos        { return s.pos }
  1623  func (s *MapUpdate) Pos() token.Pos { return s.pos }
  1624  func (s *Panic) Pos() token.Pos     { return s.pos }
  1625  func (s *Return) Pos() token.Pos    { return s.pos }
  1626  func (s *Send) Pos() token.Pos      { return s.pos }
  1627  func (s *Store) Pos() token.Pos     { return s.pos }
  1628  func (s *If) Pos() token.Pos        { return token.NoPos }
  1629  func (s *Jump) Pos() token.Pos      { return token.NoPos }
  1630  func (s *RunDefers) Pos() token.Pos { return token.NoPos }
  1631  func (s *DebugRef) Pos() token.Pos  { return s.Expr.Pos() }
  1632  
  1633  // Operands.
  1634  
  1635  func (v *Alloc) Operands(rands []*Value) []*Value {
  1636  	return rands
  1637  }
  1638  
  1639  func (v *BinOp) Operands(rands []*Value) []*Value {
  1640  	return append(rands, &v.X, &v.Y)
  1641  }
  1642  
  1643  func (c *CallCommon) Operands(rands []*Value) []*Value {
  1644  	rands = append(rands, &c.Value)
  1645  	for i := range c.Args {
  1646  		rands = append(rands, &c.Args[i])
  1647  	}
  1648  	return rands
  1649  }
  1650  
  1651  func (s *Go) Operands(rands []*Value) []*Value {
  1652  	return s.Call.Operands(rands)
  1653  }
  1654  
  1655  func (s *Call) Operands(rands []*Value) []*Value {
  1656  	return s.Call.Operands(rands)
  1657  }
  1658  
  1659  func (s *Defer) Operands(rands []*Value) []*Value {
  1660  	return s.Call.Operands(rands)
  1661  }
  1662  
  1663  func (v *ChangeInterface) Operands(rands []*Value) []*Value {
  1664  	return append(rands, &v.X)
  1665  }
  1666  
  1667  func (v *ChangeType) Operands(rands []*Value) []*Value {
  1668  	return append(rands, &v.X)
  1669  }
  1670  
  1671  func (v *Convert) Operands(rands []*Value) []*Value {
  1672  	return append(rands, &v.X)
  1673  }
  1674  
  1675  func (v *MultiConvert) Operands(rands []*Value) []*Value {
  1676  	return append(rands, &v.X)
  1677  }
  1678  
  1679  func (v *SliceToArrayPointer) Operands(rands []*Value) []*Value {
  1680  	return append(rands, &v.X)
  1681  }
  1682  
  1683  func (s *DebugRef) Operands(rands []*Value) []*Value {
  1684  	return append(rands, &s.X)
  1685  }
  1686  
  1687  func (v *Extract) Operands(rands []*Value) []*Value {
  1688  	return append(rands, &v.Tuple)
  1689  }
  1690  
  1691  func (v *Field) Operands(rands []*Value) []*Value {
  1692  	return append(rands, &v.X)
  1693  }
  1694  
  1695  func (v *FieldAddr) Operands(rands []*Value) []*Value {
  1696  	return append(rands, &v.X)
  1697  }
  1698  
  1699  func (s *If) Operands(rands []*Value) []*Value {
  1700  	return append(rands, &s.Cond)
  1701  }
  1702  
  1703  func (v *Index) Operands(rands []*Value) []*Value {
  1704  	return append(rands, &v.X, &v.Index)
  1705  }
  1706  
  1707  func (v *IndexAddr) Operands(rands []*Value) []*Value {
  1708  	return append(rands, &v.X, &v.Index)
  1709  }
  1710  
  1711  func (*Jump) Operands(rands []*Value) []*Value {
  1712  	return rands
  1713  }
  1714  
  1715  func (v *Lookup) Operands(rands []*Value) []*Value {
  1716  	return append(rands, &v.X, &v.Index)
  1717  }
  1718  
  1719  func (v *MakeChan) Operands(rands []*Value) []*Value {
  1720  	return append(rands, &v.Size)
  1721  }
  1722  
  1723  func (v *MakeClosure) Operands(rands []*Value) []*Value {
  1724  	rands = append(rands, &v.Fn)
  1725  	for i := range v.Bindings {
  1726  		rands = append(rands, &v.Bindings[i])
  1727  	}
  1728  	return rands
  1729  }
  1730  
  1731  func (v *MakeInterface) Operands(rands []*Value) []*Value {
  1732  	return append(rands, &v.X)
  1733  }
  1734  
  1735  func (v *MakeMap) Operands(rands []*Value) []*Value {
  1736  	return append(rands, &v.Reserve)
  1737  }
  1738  
  1739  func (v *MakeSlice) Operands(rands []*Value) []*Value {
  1740  	return append(rands, &v.Len, &v.Cap)
  1741  }
  1742  
  1743  func (v *MapUpdate) Operands(rands []*Value) []*Value {
  1744  	return append(rands, &v.Map, &v.Key, &v.Value)
  1745  }
  1746  
  1747  func (v *Next) Operands(rands []*Value) []*Value {
  1748  	return append(rands, &v.Iter)
  1749  }
  1750  
  1751  func (s *Panic) Operands(rands []*Value) []*Value {
  1752  	return append(rands, &s.X)
  1753  }
  1754  
  1755  func (v *Phi) Operands(rands []*Value) []*Value {
  1756  	for i := range v.Edges {
  1757  		rands = append(rands, &v.Edges[i])
  1758  	}
  1759  	return rands
  1760  }
  1761  
  1762  func (v *Range) Operands(rands []*Value) []*Value {
  1763  	return append(rands, &v.X)
  1764  }
  1765  
  1766  func (s *Return) Operands(rands []*Value) []*Value {
  1767  	for i := range s.Results {
  1768  		rands = append(rands, &s.Results[i])
  1769  	}
  1770  	return rands
  1771  }
  1772  
  1773  func (*RunDefers) Operands(rands []*Value) []*Value {
  1774  	return rands
  1775  }
  1776  
  1777  func (v *Select) Operands(rands []*Value) []*Value {
  1778  	for i := range v.States {
  1779  		rands = append(rands, &v.States[i].Chan, &v.States[i].Send)
  1780  	}
  1781  	return rands
  1782  }
  1783  
  1784  func (s *Send) Operands(rands []*Value) []*Value {
  1785  	return append(rands, &s.Chan, &s.X)
  1786  }
  1787  
  1788  func (v *Slice) Operands(rands []*Value) []*Value {
  1789  	return append(rands, &v.X, &v.Low, &v.High, &v.Max)
  1790  }
  1791  
  1792  func (s *Store) Operands(rands []*Value) []*Value {
  1793  	return append(rands, &s.Addr, &s.Val)
  1794  }
  1795  
  1796  func (v *TypeAssert) Operands(rands []*Value) []*Value {
  1797  	return append(rands, &v.X)
  1798  }
  1799  
  1800  func (v *UnOp) Operands(rands []*Value) []*Value {
  1801  	return append(rands, &v.X)
  1802  }
  1803  
  1804  // Non-Instruction Values:
  1805  func (v *Builtin) Operands(rands []*Value) []*Value   { return rands }
  1806  func (v *FreeVar) Operands(rands []*Value) []*Value   { return rands }
  1807  func (v *Const) Operands(rands []*Value) []*Value     { return rands }
  1808  func (v *Function) Operands(rands []*Value) []*Value  { return rands }
  1809  func (v *Global) Operands(rands []*Value) []*Value    { return rands }
  1810  func (v *Parameter) Operands(rands []*Value) []*Value { return rands }