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