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