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