Backport revision 203977 from trunk.
[official-gcc.git] / main / libgo / go / exp / ssa / ssa.go
blobeb0f7fc0b07904dee3fa9a801cd8116f8f2291bd
1 package ssa
3 // This package defines a high-level intermediate representation for
4 // Go programs using static single-assignment (SSA) form.
6 import (
7 "fmt"
8 "go/ast"
9 "go/token"
10 "go/types"
13 // A Program is a partial or complete Go program converted to SSA form.
14 // Each Builder creates and populates a single Program during its
15 // lifetime.
17 // TODO(adonovan): synthetic methods for promoted methods and for
18 // standalone interface methods do not belong to any package. Make
19 // them enumerable here.
21 // TODO(adonovan): MethodSets of types other than named types
22 // (i.e. anon structs) are not currently accessible, nor are they
23 // memoized. Add a method: MethodSetForType() which looks in the
24 // appropriate Package (for methods of named types) or in
25 // Program.AnonStructMethods (for methods of anon structs).
27 type Program struct {
28 Files *token.FileSet // position information for the files of this Program
29 Packages map[string]*Package // all loaded Packages, keyed by import path
30 Builtins map[types.Object]*Builtin // all built-in functions, keyed by typechecker objects.
33 // A Package is a single analyzed Go package, containing Members for
34 // all package-level functions, variables, constants and types it
35 // declares. These may be accessed directly via Members, or via the
36 // type-specific accessor methods Func, Type, Var and Const.
38 type Package struct {
39 Prog *Program // the owning program
40 Types *types.Package // the type checker's package object for this package.
41 ImportPath string // e.g. "sync/atomic"
42 Pos token.Pos // position of an arbitrary file in the package
43 Members map[string]Member // all exported and unexported members of the package
44 AnonFuncs []*Function // all anonymous functions in this package
45 Init *Function // the package's (concatenated) init function
47 // The following fields are set transiently during building,
48 // then cleared.
49 files []*ast.File // the abstract syntax tree for the files of the package
52 // A Member is a member of a Go package, implemented by *Literal,
53 // *Global, *Function, or *Type; they are created by package-level
54 // const, var, func and type declarations respectively.
56 type Member interface {
57 Name() string // the declared name of the package member
58 String() string // human-readable information about the value
59 Type() types.Type // the type of the package member
60 ImplementsMember() // dummy method to indicate the "implements" relation.
63 // An Id identifies the name of a field of a struct type, or the name
64 // of a method of an interface or a named type.
66 // For exported names, i.e. those beginning with a Unicode upper-case
67 // letter, a simple string is unambiguous.
69 // However, a method set or struct may contain multiple unexported
70 // names with identical spelling that are logically distinct because
71 // they originate in different packages. Unexported names must
72 // therefore be disambiguated by their package too.
74 // The Pkg field of an Id is therefore nil iff the name is exported.
76 // This type is suitable for use as a map key because the equivalence
77 // relation == is consistent with identifier equality.
78 type Id struct {
79 Pkg *types.Package
80 Name string
83 // A MethodSet contains all the methods whose receiver is either T or
84 // *T, for some named or struct type T.
86 // TODO(adonovan): the client is required to adapt T<=>*T, e.g. when
87 // invoking an interface method. (This could be simplified for the
88 // client by having distinct method sets for T and *T, with the SSA
89 // Builder generating wrappers as needed, but probably the client is
90 // able to do a better job.) Document the precise rules the client
91 // must follow.
93 type MethodSet map[Id]*Function
95 // A Type is a Member of a Package representing the name, underlying
96 // type and method set of a named type declared at package scope.
98 // The method set contains only concrete methods; it is empty for
99 // interface types.
101 type Type struct {
102 NamedType *types.NamedType
103 Methods MethodSet
106 // An SSA value that can be referenced by an instruction.
108 // TODO(adonovan): add methods:
109 // - Referrers() []*Instruction // all instructions that refer to this value.
111 type Value interface {
112 // Name returns the name of this value, and determines how
113 // this Value appears when used as an operand of an
114 // Instruction.
116 // This is the same as the source name for Parameters,
117 // Builtins, Functions, Captures, Globals and some Allocs.
118 // For literals, it is a representation of the literal's value
119 // and type. For all other Values this is the name of the
120 // virtual register defined by the instruction.
122 // The name of an SSA Value is not semantically significant,
123 // and may not even be unique within a function.
124 Name() string
126 // If this value is an Instruction, String returns its
127 // disassembled form; otherwise it returns unspecified
128 // human-readable information about the Value, such as its
129 // kind, name and type.
130 String() string
132 // Type returns the type of this value. Many instructions
133 // (e.g. IndexAddr) change the behaviour depending on the
134 // types of their operands.
136 // Documented type invariants below (e.g. "Alloc.Type()
137 // returns a *types.Pointer") refer to the underlying type in
138 // the case of NamedTypes.
139 Type() types.Type
141 // Dummy method to indicate the "implements" relation.
142 ImplementsValue()
145 // An Instruction is an SSA instruction that computes a new Value or
146 // has some effect.
148 // An Instruction that defines a value (e.g. BinOp) also implements
149 // the Value interface; an Instruction that only has an effect (e.g. Store)
150 // does not.
152 // TODO(adonovan): add method:
153 // - Operands() []Value // all Values referenced by this instruction.
155 type Instruction interface {
156 // String returns the disassembled form of this value. e.g.
158 // Examples of Instructions that define a Value:
159 // e.g. "x + y" (BinOp)
160 // "len([])" (Call)
161 // Note that the name of the Value is not printed.
163 // Examples of Instructions that do define (are) Values:
164 // e.g. "ret x" (Ret)
165 // "*y = x" (Store)
167 // (This separation is useful for some analyses which
168 // distinguish the operation from the value it
169 // defines. e.g. 'y = local int' is both an allocation of
170 // memory 'local int' and a definition of a pointer y.)
171 String() string
173 // Block returns the basic block to which this instruction
174 // belongs.
175 Block() *BasicBlock
177 // SetBlock sets the basic block to which this instruction
178 // belongs.
179 SetBlock(*BasicBlock)
181 // Dummy method to indicate the "implements" relation.
182 ImplementsInstruction()
185 // Function represents the parameters, results and code of a function
186 // or method.
188 // If Blocks is nil, this indicates an external function for which no
189 // Go source code is available. In this case, Captures and Locals
190 // will be nil too. Clients performing whole-program analysis must
191 // handle external functions specially.
193 // Functions are immutable values; they do not have addresses.
195 // Blocks[0] is the function entry point; block order is not otherwise
196 // semantically significant, though it may affect the readability of
197 // the disassembly.
199 // A nested function that refers to one or more lexically enclosing
200 // local variables ("free variables") has Capture parameters. Such
201 // functions cannot be called directly but require a value created by
202 // MakeClosure which, via its Bindings, supplies values for these
203 // parameters. Captures are always addresses.
205 // If the function is a method (Signature.Recv != nil) then the first
206 // element of Params is the receiver parameter.
208 // Type() returns the function's Signature.
210 type Function struct {
211 Name_ string
212 Signature *types.Signature
214 Pos token.Pos // location of the definition
215 Enclosing *Function // enclosing function if anon; nil if global
216 Pkg *Package // enclosing package; nil for some synthetic methods
217 Prog *Program // enclosing program
218 Params []*Parameter
219 FreeVars []*Capture // free variables whose values must be supplied by closure
220 Locals []*Alloc
221 Blocks []*BasicBlock // basic blocks of the function; nil => external
223 // The following fields are set transiently during building,
224 // then cleared.
225 currentBlock *BasicBlock // where to emit code
226 objects map[types.Object]Value // addresses of local variables
227 results []*Alloc // tuple of named results
228 syntax *funcSyntax // abstract syntax trees for Go source functions
229 targets *targets // linked stack of branch targets
230 lblocks map[*ast.Object]*lblock // labelled blocks
233 // An SSA basic block.
235 // The final element of Instrs is always an explicit transfer of
236 // control (If, Jump or Ret).
238 // A block may contain no Instructions only if it is unreachable,
239 // i.e. Preds is nil. Empty blocks are typically pruned.
241 // BasicBlocks and their Preds/Succs relation form a (possibly cyclic)
242 // graph independent of the SSA Value graph. It is illegal for
243 // multiple edges to exist between the same pair of blocks.
245 // The order of Preds and Succs are significant (to Phi and If
246 // instructions, respectively).
248 type BasicBlock struct {
249 Name string // label; no semantic significance
250 Func *Function // containing function
251 Instrs []Instruction // instructions in order
252 Preds, Succs []*BasicBlock // predecessors and successors
253 succs2 [2]*BasicBlock // initial space for Succs.
256 // Pure values ----------------------------------------
258 // A Capture is a pointer to a lexically enclosing local variable.
260 // The referent of a capture is an Alloc or another Capture and is
261 // always considered potentially escaping, so Captures are always
262 // addresses in the heap, and have pointer types.
264 type Capture struct {
265 Outer Value // the Value captured from the enclosing context.
268 // A Parameter represents an input parameter of a function.
270 type Parameter struct {
271 Name_ string
272 Type_ types.Type
275 // A Literal represents a literal nil, boolean, string or numeric
276 // (integer, fraction or complex) value.
278 // A literal's underlying Type() can be a basic type, possibly one of
279 // the "untyped" types. A nil literal can have any reference type:
280 // interface, map, channel, pointer, slice, or function---but not
281 // "untyped nil".
283 // All source-level constant expressions are represented by a Literal
284 // of equal type and value.
286 // Value holds the exact value of the literal, independent of its
287 // Type(), using the same representation as package go/types uses for
288 // constants.
290 // Example printed form:
291 // 42:int
292 // "hello":untyped string
293 // 3+4i:MyComplex
295 type Literal struct {
296 Type_ types.Type
297 Value interface{}
300 // A Global is a named Value holding the address of a package-level
301 // variable.
303 type Global struct {
304 Name_ string
305 Type_ types.Type
306 Pkg *Package
308 // The following fields are set transiently during building,
309 // then cleared.
310 spec *ast.ValueSpec // explained at buildGlobal
313 // A built-in function, e.g. len.
315 // Builtins are immutable values; they do not have addresses.
317 // Type() returns an inscrutable *types.builtin. Built-in functions
318 // may have polymorphic or variadic types that are not expressible in
319 // Go's type system.
321 type Builtin struct {
322 Object *types.Func // canonical types.Universe object for this built-in
325 // Value-defining instructions ----------------------------------------
327 // The Alloc instruction reserves space for a value of the given type,
328 // zero-initializes it, and yields its address.
330 // Alloc values are always addresses, and have pointer types, so the
331 // type of the allocated space is actually indirect(Type()).
333 // If Heap is false, Alloc allocates space in the function's
334 // activation record (frame); we refer to an Alloc(Heap=false) as a
335 // "local" alloc. Each local Alloc returns the same address each time
336 // it is executed within the same activation; the space is
337 // re-initialized to zero.
339 // If Heap is true, Alloc allocates space in the heap, and returns; we
340 // refer to an Alloc(Heap=true) as a "new" alloc. Each new Alloc
341 // returns a different address each time it is executed.
343 // When Alloc is applied to a channel, map or slice type, it returns
344 // the address of an uninitialized (nil) reference of that kind; store
345 // the result of MakeSlice, MakeMap or MakeChan in that location to
346 // instantiate these types.
348 // Example printed form:
349 // t0 = local int
350 // t1 = new int
352 type Alloc struct {
353 anInstruction
354 Name_ string
355 Type_ types.Type
356 Heap bool
359 // Phi represents an SSA φ-node, which combines values that differ
360 // across incoming control-flow edges and yields a new value. Within
361 // a block, all φ-nodes must appear before all non-φ nodes.
363 // Example printed form:
364 // t2 = phi [0.start: t0, 1.if.then: t1, ...]
366 type Phi struct {
367 Register
368 Edges []Value // Edges[i] is value for Block().Preds[i]
371 // Call represents a function or method call.
373 // The Call instruction yields the function result, if there is
374 // exactly one, or a tuple (empty or len>1) whose components are
375 // accessed via Extract.
377 // See CallCommon for generic function call documentation.
379 // Example printed form:
380 // t2 = println(t0, t1)
381 // t4 = t3()
382 // t7 = invoke t5.Println(...t6)
384 type Call struct {
385 Register
386 CallCommon
389 // BinOp yields the result of binary operation X Op Y.
391 // Example printed form:
392 // t1 = t0 + 1:int
394 type BinOp struct {
395 Register
396 // One of:
397 // ADD SUB MUL QUO REM + - * / %
398 // AND OR XOR SHL SHR AND_NOT & | ^ << >> &~
399 // EQL LSS GTR NEQ LEQ GEQ == != < <= < >=
400 Op token.Token
401 X, Y Value
404 // UnOp yields the result of Op X.
405 // ARROW is channel receive.
406 // MUL is pointer indirection (load).
408 // If CommaOk and Op=ARROW, the result is a 2-tuple of the value above
409 // and a boolean indicating the success of the receive. The
410 // components of the tuple are accessed using Extract.
412 // Example printed form:
413 // t0 = *x
414 // t2 = <-t1,ok
416 type UnOp struct {
417 Register
418 Op token.Token // One of: NOT SUB ARROW MUL XOR ! - <- * ^
419 X Value
420 CommaOk bool
423 // Conv yields the conversion of X to type Type().
425 // A conversion is one of the following kinds. The behaviour of the
426 // conversion operator may depend on both Type() and X.Type(), as well
427 // as the dynamic value.
429 // A '+' indicates that a dynamic representation change may occur.
430 // A '-' indicates that the conversion is a value-preserving change
431 // to types only.
433 // 1. implicit conversions (arising from assignability rules):
434 // - adding/removing a name, same underlying types.
435 // - channel type restriction, possibly adding/removing a name.
436 // 2. explicit conversions (in addition to the above):
437 // - changing a name, same underlying types.
438 // - between pointers to identical base types.
439 // + conversions between real numeric types.
440 // + conversions between complex numeric types.
441 // + integer/[]byte/[]rune -> string.
442 // + string -> []byte/[]rune.
444 // TODO(adonovan): split into two cases:
445 // - rename value (ChangeType)
446 // + value to type with different representation (Conv)
448 // Conversions of untyped string/number/bool constants to a specific
449 // representation are eliminated during SSA construction.
451 // Example printed form:
452 // t1 = convert interface{} <- int (t0)
454 type Conv struct {
455 Register
456 X Value
459 // ChangeInterface constructs a value of one interface type from a
460 // value of another interface type known to be assignable to it.
462 // Example printed form:
463 // t1 = change interface interface{} <- I (t0)
465 type ChangeInterface struct {
466 Register
467 X Value
470 // MakeInterface constructs an instance of an interface type from a
471 // value and its method-set.
473 // To construct the zero value of an interface type T, use:
474 // &Literal{types.nilType{}, T}
476 // Example printed form:
477 // t1 = make interface interface{} <- int (42:int)
479 type MakeInterface struct {
480 Register
481 X Value
482 Methods MethodSet // method set of (non-interface) X iff converting to interface
485 // A MakeClosure instruction yields an anonymous function value whose
486 // code is Fn and whose lexical capture slots are populated by Bindings.
488 // By construction, all captured variables are addresses of variables
489 // allocated with 'new', i.e. Alloc(Heap=true).
491 // Type() returns a *types.Signature.
493 // Example printed form:
494 // t0 = make closure anon@1.2 [x y z]
496 type MakeClosure struct {
497 Register
498 Fn *Function
499 Bindings []Value // values for each free variable in Fn.FreeVars
502 // The MakeMap instruction creates a new hash-table-based map object
503 // and yields a value of kind map.
505 // Type() returns a *types.Map.
507 // Example printed form:
508 // t1 = make map[string]int t0
510 type MakeMap struct {
511 Register
512 Reserve Value // initial space reservation; nil => default
515 // The MakeChan instruction creates a new channel object and yields a
516 // value of kind chan.
518 // Type() returns a *types.Chan.
520 // Example printed form:
521 // t0 = make chan int 0
523 type MakeChan struct {
524 Register
525 Size Value // int; size of buffer; zero => synchronous.
528 // MakeSlice yields a slice of length Len backed by a newly allocated
529 // array of length Cap.
531 // Both Len and Cap must be non-nil Values of integer type.
533 // (Alloc(types.Array) followed by Slice will not suffice because
534 // Alloc can only create arrays of statically known length.)
536 // Type() returns a *types.Slice.
538 // Example printed form:
539 // t1 = make slice []string 1:int t0
541 type MakeSlice struct {
542 Register
543 Len Value
544 Cap Value
547 // Slice yields a slice of an existing string, slice or *array X
548 // between optional integer bounds Low and High.
550 // Type() returns string if the type of X was string, otherwise a
551 // *types.Slice with the same element type as X.
553 // Example printed form:
554 // t1 = slice t0[1:]
556 type Slice struct {
557 Register
558 X Value // slice, string, or *array
559 Low, High Value // either may be nil
562 // FieldAddr yields the address of Field of *struct X.
564 // The field is identified by its index within the field list of the
565 // struct type of X.
567 // Type() returns a *types.Pointer.
569 // Example printed form:
570 // t1 = &t0.name [#1]
572 type FieldAddr struct {
573 Register
574 X Value // *struct
575 Field int // index into X.Type().(*types.Struct).Fields
578 // Field yields the Field of struct X.
580 // The field is identified by its index within the field list of the
581 // struct type of X; by using numeric indices we avoid ambiguity of
582 // package-local identifiers and permit compact representations.
584 // Example printed form:
585 // t1 = t0.name [#1]
587 type Field struct {
588 Register
589 X Value // struct
590 Field int // index into X.Type().(*types.Struct).Fields
593 // IndexAddr yields the address of the element at index Index of
594 // collection X. Index is an integer expression.
596 // The elements of maps and strings are not addressable; use Lookup or
597 // MapUpdate instead.
599 // Type() returns a *types.Pointer.
601 // Example printed form:
602 // t2 = &t0[t1]
604 type IndexAddr struct {
605 Register
606 X Value // slice or *array,
607 Index Value // numeric index
610 // Index yields element Index of array X.
612 // TODO(adonovan): permit X to have type slice.
613 // Currently this requires IndexAddr followed by Load.
615 // Example printed form:
616 // t2 = t0[t1]
618 type Index struct {
619 Register
620 X Value // array
621 Index Value // integer index
624 // Lookup yields element Index of collection X, a map or string.
625 // Index is an integer expression if X is a string or the appropriate
626 // key type if X is a map.
628 // If CommaOk, the result is a 2-tuple of the value above and a
629 // boolean indicating the result of a map membership test for the key.
630 // The components of the tuple are accessed using Extract.
632 // Example printed form:
633 // t2 = t0[t1]
634 // t5 = t3[t4],ok
636 type Lookup struct {
637 Register
638 X Value // string or map
639 Index Value // numeric or key-typed index
640 CommaOk bool // return a value,ok pair
643 // SelectState is a helper for Select.
644 // It represents one goal state and its corresponding communication.
646 type SelectState struct {
647 Dir ast.ChanDir // direction of case
648 Chan Value // channel to use (for send or receive)
649 Send Value // value to send (for send)
652 // Select tests whether (or blocks until) one or more of the specified
653 // sent or received states is entered.
655 // It returns a triple (index int, recv ?, recvOk bool) whose
656 // components, described below, must be accessed via the Extract
657 // instruction.
659 // If Blocking, select waits until exactly one state holds, i.e. a
660 // channel becomes ready for the designated operation of sending or
661 // receiving; select chooses one among the ready states
662 // pseudorandomly, performs the send or receive operation, and sets
663 // 'index' to the index of the chosen channel.
665 // If !Blocking, select doesn't block if no states hold; instead it
666 // returns immediately with index equal to -1.
668 // If the chosen channel was used for a receive, 'recv' is set to the
669 // received value; Otherwise it is unspecified. recv has no useful
670 // type since it is conceptually the union of all possible received
671 // values.
673 // The third component of the triple, recvOk, is a boolean whose value
674 // is true iff the selected operation was a receive and the receive
675 // successfully yielded a value.
677 // Example printed form:
678 // t3 = select nonblocking [<-t0, t1<-t2, ...]
679 // t4 = select blocking []
681 type Select struct {
682 Register
683 States []SelectState
684 Blocking bool
687 // Range yields an iterator over the domain and range of X.
688 // Elements are accessed via Next.
690 // Type() returns a *types.Result (tuple type).
692 // Example printed form:
693 // t0 = range "hello":string
695 type Range struct {
696 Register
697 X Value // array, *array, slice, string, map or chan
700 // Next reads and advances the iterator Iter and returns a 3-tuple
701 // value (ok, k, v). If the iterator is not exhausted, ok is true and
702 // k and v are the next elements of the domain and range,
703 // respectively. Otherwise ok is false and k and v are undefined.
705 // For channel iterators, k is the received value and v is always
706 // undefined.
708 // Components of the tuple are accessed using Extract.
710 // Type() returns a *types.Result (tuple type).
712 // Example printed form:
713 // t1 = next t0
715 type Next struct {
716 Register
717 Iter Value
720 // TypeAssert tests whether interface value X has type
721 // AssertedType.
723 // If CommaOk: on success it returns a pair (v, true) where v is a
724 // copy of value X; on failure it returns (z, false) where z is the
725 // zero value of that type. The components of the pair must be
726 // accessed using the Extract instruction.
728 // If !CommaOk, on success it returns just the single value v; on
729 // failure it panics.
731 // Type() reflects the actual type of the result, possibly a pair
732 // (types.Result); AssertedType is the asserted type.
734 // Example printed form:
735 // t1 = typeassert t0.(int)
736 // t3 = typeassert,ok t2.(T)
738 type TypeAssert struct {
739 Register
740 X Value
741 AssertedType types.Type
742 CommaOk bool
745 // Extract yields component Index of Tuple.
747 // This is used to access the results of instructions with multiple
748 // return values, such as Call, TypeAssert, Next, UnOp(ARROW) and
749 // IndexExpr(Map).
751 // Example printed form:
752 // t1 = extract t0 #1
754 type Extract struct {
755 Register
756 Tuple Value
757 Index int
760 // Instructions executed for effect. They do not yield a value. --------------------
762 // Jump transfers control to the sole successor of its owning block.
764 // A Jump instruction must be the last instruction of its containing
765 // BasicBlock.
767 // Example printed form:
768 // jump done
770 type Jump struct {
771 anInstruction
774 // The If instruction transfers control to one of the two successors
775 // of its owning block, depending on the boolean Cond: the first if
776 // true, the second if false.
778 // An If instruction must be the last instruction of its containing
779 // BasicBlock.
781 // Example printed form:
782 // if t0 goto done else body
784 type If struct {
785 anInstruction
786 Cond Value
789 // Ret returns values and control back to the calling function.
791 // len(Results) is always equal to the number of results in the
792 // function's signature. A source-level 'return' statement with no
793 // operands in a multiple-return value function is desugared to make
794 // the results explicit.
796 // If len(Results) > 1, Ret returns a tuple value with the specified
797 // components which the caller must access using Extract instructions.
799 // There is no instruction to return a ready-made tuple like those
800 // returned by a "value,ok"-mode TypeAssert, Lookup or UnOp(ARROW) or
801 // a tail-call to a function with multiple result parameters.
802 // TODO(adonovan): consider defining one; but: dis- and re-assembling
803 // the tuple is unavoidable if assignability conversions are required
804 // on the components.
806 // Ret must be the last instruction of its containing BasicBlock.
807 // Such a block has no successors.
809 // Example printed form:
810 // ret
811 // ret nil:I, 2:int
813 type Ret struct {
814 anInstruction
815 Results []Value
818 // Go creates a new goroutine and calls the specified function
819 // within it.
821 // See CallCommon for generic function call documentation.
823 // Example printed form:
824 // go println(t0, t1)
825 // go t3()
826 // go invoke t5.Println(...t6)
828 type Go struct {
829 anInstruction
830 CallCommon
833 // Defer pushes the specified call onto a stack of functions
834 // to be called immediately prior to returning from the
835 // current function.
837 // See CallCommon for generic function call documentation.
839 // Example printed form:
840 // defer println(t0, t1)
841 // defer t3()
842 // defer invoke t5.Println(...t6)
844 type Defer struct {
845 anInstruction
846 CallCommon
849 // Send sends X on channel Chan.
851 // Example printed form:
852 // send t0 <- t1
854 type Send struct {
855 anInstruction
856 Chan, X Value
859 // Store stores Val at address Addr.
860 // Stores can be of arbitrary types.
862 // Example printed form:
863 // *x = y
865 type Store struct {
866 anInstruction
867 Addr Value
868 Val Value
871 // MapUpdate updates the association of Map[Key] to Value.
873 // Example printed form:
874 // t0[t1] = t2
876 type MapUpdate struct {
877 anInstruction
878 Map Value
879 Key Value
880 Value Value
883 // Embeddable mix-ins used for common parts of other structs. --------------------
885 // Register is a mix-in embedded by all SSA values that are also
886 // instructions, i.e. virtual registers, and provides implementations
887 // of the Value interface's Name() and Type() methods: the name is
888 // simply a numbered register (e.g. "t0") and the type is the Type_
889 // field.
891 // Temporary names are automatically assigned to each Register on
892 // completion of building a function in SSA form.
894 // Clients must not assume that the 'id' value (and the Name() derived
895 // from it) is unique within a function. As always in this API,
896 // semantics are determined only by identity; names exist only to
897 // facilitate debugging.
899 type Register struct {
900 anInstruction
901 num int // "name" of virtual register, e.g. "t0". Not guaranteed unique.
902 Type_ types.Type // type of virtual register
905 // AnInstruction is a mix-in embedded by all Instructions.
906 // It provides the implementations of the Block and SetBlock methods.
907 type anInstruction struct {
908 Block_ *BasicBlock // the basic block of this instruction
911 // CallCommon is a mix-in embedded by Go, Defer and Call to hold the
912 // common parts of a function or method call.
914 // Each CallCommon exists in one of two modes, function call and
915 // interface method invocation, or "call" and "invoke" for short.
917 // 1. "call" mode: when Recv is nil, a CallCommon represents an
918 // ordinary function call of the value in Func.
920 // In the common case in which Func is a *Function, this indicates a
921 // statically dispatched call to a package-level function, an
922 // anonymous function, or a method of a named type. Also statically
923 // dispatched, but less common, Func may be a *MakeClosure, indicating
924 // an immediately applied function literal with free variables. Any
925 // other Value of Func indicates a dynamically dispatched function
926 // call.
928 // Args contains the arguments to the call. If Func is a method,
929 // Args[0] contains the receiver parameter. Recv and Method are not
930 // used in this mode.
932 // Example printed form:
933 // t2 = println(t0, t1)
934 // go t3()
935 // defer t5(...t6)
937 // 2. "invoke" mode: when Recv is non-nil, a CallCommon represents a
938 // dynamically dispatched call to an interface method. In this
939 // mode, Recv is the interface value and Method is the index of the
940 // method within the interface type of the receiver.
942 // Recv is implicitly supplied to the concrete method implementation
943 // as the receiver parameter; in other words, Args[0] holds not the
944 // receiver but the first true argument. Func is not used in this
945 // mode.
947 // Example printed form:
948 // t1 = invoke t0.String()
949 // go invoke t3.Run(t2)
950 // defer invoke t4.Handle(...t5)
952 // In both modes, HasEllipsis is true iff the last element of Args is
953 // a slice value containing zero or more arguments to a variadic
954 // function. (This is not semantically significant since the type of
955 // the called function is sufficient to determine this, but it aids
956 // readability of the printed form.)
958 type CallCommon struct {
959 Recv Value // receiver, iff interface method invocation
960 Method int // index of interface method within Recv.Type().(*types.Interface).Methods
961 Func Value // target of call, iff function call
962 Args []Value // actual parameters, including receiver in invoke mode
963 HasEllipsis bool // true iff last Args is a slice (needed?)
964 Pos token.Pos // position of call expression
967 func (v *Builtin) Type() types.Type { return v.Object.GetType() }
968 func (v *Builtin) Name() string { return v.Object.GetName() }
970 func (v *Capture) Type() types.Type { return v.Outer.Type() }
971 func (v *Capture) Name() string { return v.Outer.Name() }
973 func (v *Global) Type() types.Type { return v.Type_ }
974 func (v *Global) Name() string { return v.Name_ }
976 func (v *Function) Name() string { return v.Name_ }
977 func (v *Function) Type() types.Type { return v.Signature }
979 func (v *Parameter) Type() types.Type { return v.Type_ }
980 func (v *Parameter) Name() string { return v.Name_ }
982 func (v *Alloc) Type() types.Type { return v.Type_ }
983 func (v *Alloc) Name() string { return v.Name_ }
985 func (v *Register) Type() types.Type { return v.Type_ }
986 func (v *Register) setType(typ types.Type) { v.Type_ = typ }
987 func (v *Register) Name() string { return fmt.Sprintf("t%d", v.num) }
988 func (v *Register) setNum(num int) { v.num = num }
990 func (v *anInstruction) Block() *BasicBlock { return v.Block_ }
991 func (v *anInstruction) SetBlock(block *BasicBlock) { v.Block_ = block }
993 func (ms *Type) Type() types.Type { return ms.NamedType }
994 func (ms *Type) String() string { return ms.Name() }
995 func (ms *Type) Name() string { return ms.NamedType.Obj.Name }
997 func (p *Package) Name() string { return p.Types.Name }
999 // Func returns the package-level function of the specified name,
1000 // or nil if not found.
1002 func (p *Package) Func(name string) (f *Function) {
1003 f, _ = p.Members[name].(*Function)
1004 return
1007 // Var returns the package-level variable of the specified name,
1008 // or nil if not found.
1010 func (p *Package) Var(name string) (g *Global) {
1011 g, _ = p.Members[name].(*Global)
1012 return
1015 // Const returns the package-level constant of the specified name,
1016 // or nil if not found.
1018 func (p *Package) Const(name string) (l *Literal) {
1019 l, _ = p.Members[name].(*Literal)
1020 return
1023 // Type returns the package-level type of the specified name,
1024 // or nil if not found.
1026 func (p *Package) Type(name string) (t *Type) {
1027 t, _ = p.Members[name].(*Type)
1028 return
1031 // "Implements" relation boilerplate.
1032 // Don't try to factor this using promotion and mix-ins: the long-hand
1033 // form serves as better documentation, including in godoc.
1035 func (*Alloc) ImplementsValue() {}
1036 func (*BinOp) ImplementsValue() {}
1037 func (*Builtin) ImplementsValue() {}
1038 func (*Call) ImplementsValue() {}
1039 func (*Capture) ImplementsValue() {}
1040 func (*ChangeInterface) ImplementsValue() {}
1041 func (*Conv) ImplementsValue() {}
1042 func (*Extract) ImplementsValue() {}
1043 func (*Field) ImplementsValue() {}
1044 func (*FieldAddr) ImplementsValue() {}
1045 func (*Function) ImplementsValue() {}
1046 func (*Global) ImplementsValue() {}
1047 func (*Index) ImplementsValue() {}
1048 func (*IndexAddr) ImplementsValue() {}
1049 func (*Literal) ImplementsValue() {}
1050 func (*Lookup) ImplementsValue() {}
1051 func (*MakeChan) ImplementsValue() {}
1052 func (*MakeClosure) ImplementsValue() {}
1053 func (*MakeInterface) ImplementsValue() {}
1054 func (*MakeMap) ImplementsValue() {}
1055 func (*MakeSlice) ImplementsValue() {}
1056 func (*Next) ImplementsValue() {}
1057 func (*Parameter) ImplementsValue() {}
1058 func (*Phi) ImplementsValue() {}
1059 func (*Range) ImplementsValue() {}
1060 func (*Select) ImplementsValue() {}
1061 func (*Slice) ImplementsValue() {}
1062 func (*TypeAssert) ImplementsValue() {}
1063 func (*UnOp) ImplementsValue() {}
1065 func (*Function) ImplementsMember() {}
1066 func (*Global) ImplementsMember() {}
1067 func (*Literal) ImplementsMember() {}
1068 func (*Type) ImplementsMember() {}
1070 func (*Alloc) ImplementsInstruction() {}
1071 func (*BinOp) ImplementsInstruction() {}
1072 func (*Call) ImplementsInstruction() {}
1073 func (*ChangeInterface) ImplementsInstruction() {}
1074 func (*Conv) ImplementsInstruction() {}
1075 func (*Defer) ImplementsInstruction() {}
1076 func (*Extract) ImplementsInstruction() {}
1077 func (*Field) ImplementsInstruction() {}
1078 func (*FieldAddr) ImplementsInstruction() {}
1079 func (*Go) ImplementsInstruction() {}
1080 func (*If) ImplementsInstruction() {}
1081 func (*Index) ImplementsInstruction() {}
1082 func (*IndexAddr) ImplementsInstruction() {}
1083 func (*Jump) ImplementsInstruction() {}
1084 func (*Lookup) ImplementsInstruction() {}
1085 func (*MakeChan) ImplementsInstruction() {}
1086 func (*MakeClosure) ImplementsInstruction() {}
1087 func (*MakeInterface) ImplementsInstruction() {}
1088 func (*MakeMap) ImplementsInstruction() {}
1089 func (*MakeSlice) ImplementsInstruction() {}
1090 func (*MapUpdate) ImplementsInstruction() {}
1091 func (*Next) ImplementsInstruction() {}
1092 func (*Phi) ImplementsInstruction() {}
1093 func (*Range) ImplementsInstruction() {}
1094 func (*Ret) ImplementsInstruction() {}
1095 func (*Select) ImplementsInstruction() {}
1096 func (*Send) ImplementsInstruction() {}
1097 func (*Slice) ImplementsInstruction() {}
1098 func (*Store) ImplementsInstruction() {}
1099 func (*TypeAssert) ImplementsInstruction() {}
1100 func (*UnOp) ImplementsInstruction() {}