diff options
Diffstat (limited to 'gcc-4.8.1/libgo/go/exp/ssa')
-rw-r--r-- | gcc-4.8.1/libgo/go/exp/ssa/blockopt.go | 186 | ||||
-rw-r--r-- | gcc-4.8.1/libgo/go/exp/ssa/doc.go | 113 | ||||
-rw-r--r-- | gcc-4.8.1/libgo/go/exp/ssa/func.go | 428 | ||||
-rw-r--r-- | gcc-4.8.1/libgo/go/exp/ssa/literal.go | 137 | ||||
-rw-r--r-- | gcc-4.8.1/libgo/go/exp/ssa/print.go | 383 | ||||
-rw-r--r-- | gcc-4.8.1/libgo/go/exp/ssa/sanity.go | 263 | ||||
-rw-r--r-- | gcc-4.8.1/libgo/go/exp/ssa/ssa.go | 1100 | ||||
-rw-r--r-- | gcc-4.8.1/libgo/go/exp/ssa/util.go | 172 |
8 files changed, 0 insertions, 2782 deletions
diff --git a/gcc-4.8.1/libgo/go/exp/ssa/blockopt.go b/gcc-4.8.1/libgo/go/exp/ssa/blockopt.go deleted file mode 100644 index a81be6aef..000000000 --- a/gcc-4.8.1/libgo/go/exp/ssa/blockopt.go +++ /dev/null @@ -1,186 +0,0 @@ -package ssa - -// Simple block optimisations to simplify the control flow graph. - -// TODO(adonovan): instead of creating several "unreachable" blocks -// per function in the Builder, reuse a single one (e.g. at Blocks[1]) -// to reduce garbage. - -import ( - "fmt" - "os" -) - -// If true, perform sanity checking and show progress at each -// successive iteration of optimizeBlocks. Very verbose. -const debugBlockOpt = false - -func hasPhi(b *BasicBlock) bool { - _, ok := b.Instrs[0].(*Phi) - return ok -} - -// prune attempts to prune block b if it is unreachable (i.e. has no -// predecessors other than itself), disconnecting it from the CFG. -// The result is true if the optimisation was applied. i is the block -// index within the function. -// -func prune(f *Function, i int, b *BasicBlock) bool { - if i == 0 { - return false // don't prune entry block - } - if len(b.Preds) == 0 || len(b.Preds) == 1 && b.Preds[0] == b { - // Disconnect it from its successors. - for _, c := range b.Succs { - c.removePred(b) - } - if debugBlockOpt { - fmt.Fprintln(os.Stderr, "prune", b.Name) - } - - // Delete b. - f.Blocks[i] = nil - return true - } - return false -} - -// jumpThreading attempts to apply simple jump-threading to block b, -// in which a->b->c become a->c if b is just a Jump. -// The result is true if the optimisation was applied. -// i is the block index within the function. -// -func jumpThreading(f *Function, i int, b *BasicBlock) bool { - if i == 0 { - return false // don't apply to entry block - } - if b.Instrs == nil { - fmt.Println("empty block ", b.Name) - return false - } - if _, ok := b.Instrs[0].(*Jump); !ok { - return false // not just a jump - } - c := b.Succs[0] - if c == b { - return false // don't apply to degenerate jump-to-self. - } - if hasPhi(c) { - return false // not sound without more effort - } - for j, a := range b.Preds { - a.replaceSucc(b, c) - - // If a now has two edges to c, replace its degenerate If by Jump. - if len(a.Succs) == 2 && a.Succs[0] == c && a.Succs[1] == c { - jump := new(Jump) - jump.SetBlock(a) - a.Instrs[len(a.Instrs)-1] = jump - a.Succs = a.Succs[:1] - c.removePred(b) - } else { - if j == 0 { - c.replacePred(b, a) - } else { - c.Preds = append(c.Preds, a) - } - } - - if debugBlockOpt { - fmt.Fprintln(os.Stderr, "jumpThreading", a.Name, b.Name, c.Name) - } - } - f.Blocks[i] = nil - return true -} - -// fuseBlocks attempts to apply the block fusion optimisation to block -// a, in which a->b becomes ab if len(a.Succs)==len(b.Preds)==1. -// The result is true if the optimisation was applied. -// -func fuseBlocks(f *Function, a *BasicBlock) bool { - if len(a.Succs) != 1 { - return false - } - b := a.Succs[0] - if len(b.Preds) != 1 { - return false - } - // Eliminate jump at end of A, then copy all of B across. - a.Instrs = append(a.Instrs[:len(a.Instrs)-1], b.Instrs...) - for _, instr := range b.Instrs { - instr.SetBlock(a) - } - - // A inherits B's successors - a.Succs = append(a.succs2[:0], b.Succs...) - - // Fix up Preds links of all successors of B. - for _, c := range b.Succs { - c.replacePred(b, a) - } - - if debugBlockOpt { - fmt.Fprintln(os.Stderr, "fuseBlocks", a.Name, b.Name) - } - - // Make b unreachable. Subsequent pruning will reclaim it. - b.Preds = nil - return true -} - -// optimizeBlocks() performs some simple block optimizations on a -// completed function: dead block elimination, block fusion, jump -// threading. -// -func optimizeBlocks(f *Function) { - // Loop until no further progress. - changed := true - for changed { - changed = false - - if debugBlockOpt { - f.DumpTo(os.Stderr) - MustSanityCheck(f, nil) - } - - for i, b := range f.Blocks { - // f.Blocks will temporarily contain nils to indicate - // deleted blocks; we remove them at the end. - if b == nil { - continue - } - - // Prune unreachable blocks (including all empty blocks). - if prune(f, i, b) { - changed = true - continue // (b was pruned) - } - - // Fuse blocks. b->c becomes bc. - if fuseBlocks(f, b) { - changed = true - } - - // a->b->c becomes a->c if b contains only a Jump. - if jumpThreading(f, i, b) { - changed = true - continue // (b was disconnected) - } - } - } - - // Eliminate nils from Blocks. - j := 0 - for _, b := range f.Blocks { - if b != nil { - f.Blocks[j] = b - j++ - } - } - // Nil out b.Blocks[j:] to aid GC. - for i := j; i < len(f.Blocks); i++ { - f.Blocks[i] = nil - } - f.Blocks = f.Blocks[:j] -} diff --git a/gcc-4.8.1/libgo/go/exp/ssa/doc.go b/gcc-4.8.1/libgo/go/exp/ssa/doc.go deleted file mode 100644 index a489c3129..000000000 --- a/gcc-4.8.1/libgo/go/exp/ssa/doc.go +++ /dev/null @@ -1,113 +0,0 @@ -// Package ssa defines a representation of the elements of Go programs -// (packages, types, functions, variables and constants) using a -// static single-assignment (SSA) form intermediate representation -// (IR) for the the bodies of functions. -// -// THIS INTERFACE IS EXPERIMENTAL AND IS LIKELY TO CHANGE. -// -// For an introduction to SSA form, see -// http://en.wikipedia.org/wiki/Static_single_assignment_form. -// This page provides a broader reading list: -// http://www.dcs.gla.ac.uk/~jsinger/ssa.html. -// -// The level of abstraction of the SSA form is intentionally close to -// the source language to facilitate construction of source analysis -// tools. It is not primarily intended for machine code generation. -// -// All looping, branching and switching constructs are replaced with -// unstructured control flow. We may add higher-level control flow -// primitives in the future to facilitate constant-time dispatch of -// switch statements, for example. -// -// Builder encapsulates the tasks of type-checking (using go/types) -// abstract syntax trees (as defined by go/ast) for the source files -// comprising a Go program, and the conversion of each function from -// Go ASTs to the SSA representation. -// -// By supplying an instance of the SourceLocator function prototype, -// clients may control how the builder locates, loads and parses Go -// sources files for imported packages. This package provides -// GorootLoader, which uses go/build to locate packages in the Go -// source distribution, and go/parser to parse them. -// -// The builder initially builds a naive SSA form in which all local -// variables are addresses of stack locations with explicit loads and -// stores. If desired, registerisation and φ-node insertion using -// dominance and dataflow can be performed as a later pass to improve -// the accuracy and performance of subsequent analyses; this pass is -// not yet implemented. -// -// The program representation constructed by this package is fully -// resolved internally, i.e. it does not rely on the names of Values, -// Packages, Functions, Types or BasicBlocks for the correct -// interpretation of the program. Only the identities of objects and -// the topology of the SSA and type graphs are semantically -// significant. (There is one exception: Ids, used to identify field -// and method names, contain strings.) Avoidance of name-based -// operations simplifies the implementation of subsequent passes and -// can make them very efficient. Many objects are nonetheless named -// to aid in debugging, but it is not essential that the names be -// either accurate or unambiguous. The public API exposes a number of -// name-based maps for client convenience. -// -// Given a Go source package such as this: -// -// package main -// -// import "fmt" -// -// const message = "Hello, World!" -// -// func hello() { -// fmt.Println(message) -// } -// -// The SSA Builder creates a *Program containing a main *Package such -// as this: -// -// Package(Name: "main") -// Members: -// "message": *Literal (Type: untyped string, Value: "Hello, World!") -// "init·guard": *Global (Type: *bool) -// "hello": *Function (Type: func()) -// Init: *Function (Type: func()) -// -// The printed representation of the function main.hello is shown -// below. Within the function listing, the name of each BasicBlock -// such as ".0.entry" is printed left-aligned, followed by the block's -// instructions, i.e. implementations of Instruction. -// For each instruction that defines an SSA virtual register -// (i.e. implements Value), the type of that value is shown in the -// right column. -// -// # Name: main.hello -// # Declared at hello.go:7:6 -// # Type: func() -// func hello(): -// .0.entry: -// t0 = new [1]interface{} *[1]interface{} -// t1 = &t0[0:untyped integer] *interface{} -// t2 = make interface interface{} <- string ("Hello, World!":string) interface{} -// *t1 = t2 -// t3 = slice t0[:] []interface{} -// t4 = fmt.Println(t3) (n int, err error) -// ret -// -// TODO(adonovan): demonstrate more features in the example: -// parameters and control flow at the least. -// -// TODO(adonovan): Consider how token.Pos source location information -// should be made available generally. Currently it is only present in -// Package, Function and CallCommon. -// -// TODO(adonovan): Provide an example skeleton application that loads -// and dumps the SSA form of a program. Accommodate package-at-a-time -// vs. whole-program operation. -// -// TODO(adonovan): Consider the exceptional control-flow implications -// of defer and recover(). -// -// TODO(adonovan): build tables/functions that relate source variables -// to SSA variables to assist user interfaces that make queries about -// specific source entities. -package ssa diff --git a/gcc-4.8.1/libgo/go/exp/ssa/func.go b/gcc-4.8.1/libgo/go/exp/ssa/func.go deleted file mode 100644 index 6af5e1efc..000000000 --- a/gcc-4.8.1/libgo/go/exp/ssa/func.go +++ /dev/null @@ -1,428 +0,0 @@ -package ssa - -// This file implements the Function and BasicBlock types. - -import ( - "fmt" - "go/ast" - "go/types" - "io" - "os" -) - -// Mode bits for additional diagnostics and checking. -// TODO(adonovan): move these to builder.go once submitted. -type BuilderMode uint - -const ( - LogPackages BuilderMode = 1 << iota // Dump package inventory to stderr - LogFunctions // Dump function SSA code to stderr - LogSource // Show source locations as SSA builder progresses - SanityCheckFunctions // Perform sanity checking of function bodies - UseGCImporter // Ignore SourceLoader; use gc-compiled object code for all imports -) - -// addEdge adds a control-flow graph edge from from to to. -func addEdge(from, to *BasicBlock) { - from.Succs = append(from.Succs, to) - to.Preds = append(to.Preds, from) -} - -// emit appends an instruction to the current basic block. -// If the instruction defines a Value, it is returned. -// -func (b *BasicBlock) emit(i Instruction) Value { - i.SetBlock(b) - b.Instrs = append(b.Instrs, i) - v, _ := i.(Value) - return v -} - -// phis returns the prefix of b.Instrs containing all the block's φ-nodes. -func (b *BasicBlock) phis() []Instruction { - for i, instr := range b.Instrs { - if _, ok := instr.(*Phi); !ok { - return b.Instrs[:i] - } - } - return nil // unreachable in well-formed blocks -} - -// replacePred replaces all occurrences of p in b's predecessor list with q. -// Ordinarily there should be at most one. -// -func (b *BasicBlock) replacePred(p, q *BasicBlock) { - for i, pred := range b.Preds { - if pred == p { - b.Preds[i] = q - } - } -} - -// replaceSucc replaces all occurrences of p in b's successor list with q. -// Ordinarily there should be at most one. -// -func (b *BasicBlock) replaceSucc(p, q *BasicBlock) { - for i, succ := range b.Succs { - if succ == p { - b.Succs[i] = q - } - } -} - -// removePred removes all occurrences of p in b's -// predecessor list and φ-nodes. -// Ordinarily there should be at most one. -// -func (b *BasicBlock) removePred(p *BasicBlock) { - phis := b.phis() - - // We must preserve edge order for φ-nodes. - j := 0 - for i, pred := range b.Preds { - if pred != p { - b.Preds[j] = b.Preds[i] - // Strike out φ-edge too. - for _, instr := range phis { - phi := instr.(*Phi) - phi.Edges[j] = phi.Edges[i] - } - j++ - } - } - // Nil out b.Preds[j:] and φ-edges[j:] to aid GC. - for i := j; i < len(b.Preds); i++ { - b.Preds[i] = nil - for _, instr := range phis { - instr.(*Phi).Edges[i] = nil - } - } - b.Preds = b.Preds[:j] - for _, instr := range phis { - phi := instr.(*Phi) - phi.Edges = phi.Edges[:j] - } -} - -// Destinations associated with unlabelled for/switch/select stmts. -// We push/pop one of these as we enter/leave each construct and for -// each BranchStmt we scan for the innermost target of the right type. -// -type targets struct { - tail *targets // rest of stack - _break *BasicBlock - _continue *BasicBlock - _fallthrough *BasicBlock -} - -// Destinations associated with a labelled block. -// We populate these as labels are encountered in forward gotos or -// labelled statements. -// -type lblock struct { - _goto *BasicBlock - _break *BasicBlock - _continue *BasicBlock -} - -// funcSyntax holds the syntax tree for the function declaration and body. -type funcSyntax struct { - recvField *ast.FieldList - paramFields *ast.FieldList - resultFields *ast.FieldList - body *ast.BlockStmt -} - -// labelledBlock returns the branch target associated with the -// specified label, creating it if needed. -// -func (f *Function) labelledBlock(label *ast.Ident) *lblock { - lb := f.lblocks[label.Obj] - if lb == nil { - lb = &lblock{_goto: f.newBasicBlock("label." + label.Name)} - f.lblocks[label.Obj] = lb - } - return lb -} - -// addParam adds a (non-escaping) parameter to f.Params of the -// specified name and type. -// -func (f *Function) addParam(name string, typ types.Type) *Parameter { - v := &Parameter{ - Name_: name, - Type_: typ, - } - f.Params = append(f.Params, v) - return v -} - -// addSpilledParam declares a parameter that is pre-spilled to the -// stack; the function body will load/store the spilled location. -// Subsequent registerization will eliminate spills where possible. -// -func (f *Function) addSpilledParam(obj types.Object) { - name := obj.GetName() - param := f.addParam(name, obj.GetType()) - spill := &Alloc{ - Name_: name + "~", // "~" means "spilled" - Type_: pointer(obj.GetType()), - } - f.objects[obj] = spill - f.Locals = append(f.Locals, spill) - f.emit(spill) - f.emit(&Store{Addr: spill, Val: param}) -} - -// start initializes the function prior to generating SSA code for its body. -// Precondition: f.Type() already set. -// -// If f.syntax != nil, f is a Go source function and idents must be a -// mapping from syntactic identifiers to their canonical type objects; -// Otherwise, idents is ignored and the usual set-up for Go source -// functions is skipped. -// -func (f *Function) start(mode BuilderMode, idents map[*ast.Ident]types.Object) { - if mode&LogSource != 0 { - fmt.Fprintf(os.Stderr, "build function %s @ %s\n", f.FullName(), f.Prog.Files.Position(f.Pos)) - } - f.currentBlock = f.newBasicBlock("entry") - f.objects = make(map[types.Object]Value) // needed for some synthetics, e.g. init - if f.syntax == nil { - return // synthetic function; no syntax tree - } - f.lblocks = make(map[*ast.Object]*lblock) - - // Receiver (at most one inner iteration). - if f.syntax.recvField != nil { - for _, field := range f.syntax.recvField.List { - for _, n := range field.Names { - f.addSpilledParam(idents[n]) - } - if field.Names == nil { - f.addParam(f.Signature.Recv.Name, f.Signature.Recv.Type) - } - } - } - - // Parameters. - if f.syntax.paramFields != nil { - for _, field := range f.syntax.paramFields.List { - for _, n := range field.Names { - f.addSpilledParam(idents[n]) - } - } - } - - // Results. - if f.syntax.resultFields != nil { - for _, field := range f.syntax.resultFields.List { - // Implicit "var" decl of locals for named results. - for _, n := range field.Names { - f.results = append(f.results, f.addNamedLocal(idents[n])) - } - } - } -} - -// finish() finalizes the function after SSA code generation of its body. -func (f *Function) finish(mode BuilderMode) { - f.objects = nil - f.results = nil - f.currentBlock = nil - f.lblocks = nil - f.syntax = nil - - // Remove any f.Locals that are now heap-allocated. - j := 0 - for _, l := range f.Locals { - if !l.Heap { - f.Locals[j] = l - j++ - } - } - // Nil out f.Locals[j:] to aid GC. - for i := j; i < len(f.Locals); i++ { - f.Locals[i] = nil - } - f.Locals = f.Locals[:j] - - // Ensure all value-defining Instructions have register names. - // (Non-Instruction Values are named at construction.) - tmp := 0 - for _, b := range f.Blocks { - for _, instr := range b.Instrs { - switch instr := instr.(type) { - case *Alloc: - // Local Allocs may already be named. - if instr.Name_ == "" { - instr.Name_ = fmt.Sprintf("t%d", tmp) - tmp++ - } - case Value: - instr.(interface { - setNum(int) - }).setNum(tmp) - tmp++ - } - } - } - optimizeBlocks(f) - - if mode&LogFunctions != 0 { - f.DumpTo(os.Stderr) - } - if mode&SanityCheckFunctions != 0 { - MustSanityCheck(f, nil) - } - if mode&LogSource != 0 { - fmt.Fprintf(os.Stderr, "build function %s done\n", f.FullName()) - } -} - -// addNamedLocal creates a local variable, adds it to function f and -// returns it. Its name and type are taken from obj. Subsequent -// calls to f.lookup(obj) will return the same local. -// -// Precondition: f.syntax != nil (i.e. a Go source function). -// -func (f *Function) addNamedLocal(obj types.Object) *Alloc { - l := f.addLocal(obj.GetType()) - l.Name_ = obj.GetName() - f.objects[obj] = l - return l -} - -// addLocal creates an anonymous local variable of type typ, adds it -// to function f and returns it. -// -func (f *Function) addLocal(typ types.Type) *Alloc { - v := &Alloc{Type_: pointer(typ)} - f.Locals = append(f.Locals, v) - f.emit(v) - return v -} - -// lookup returns the address of the named variable identified by obj -// that is local to function f or one of its enclosing functions. -// If escaping, the reference comes from a potentially escaping pointer -// expression and the referent must be heap-allocated. -// -func (f *Function) lookup(obj types.Object, escaping bool) Value { - if v, ok := f.objects[obj]; ok { - if escaping { - // Walk up the chain of Captures. - x := v - for { - if c, ok := x.(*Capture); ok { - x = c.Outer - } else { - break - } - } - // By construction, all captures are ultimately Allocs in the - // naive SSA form. Parameters are pre-spilled to the stack. - x.(*Alloc).Heap = true - } - return v // function-local var (address) - } - - // Definition must be in an enclosing function; - // plumb it through intervening closures. - if f.Enclosing == nil { - panic("no Value for type.Object " + obj.GetName()) - } - v := &Capture{f.Enclosing.lookup(obj, true)} // escaping - f.objects[obj] = v - f.FreeVars = append(f.FreeVars, v) - return v -} - -// emit emits the specified instruction to function f, updating the -// control-flow graph if required. -// -func (f *Function) emit(instr Instruction) Value { - return f.currentBlock.emit(instr) -} - -// DumpTo prints to w a human readable "disassembly" of the SSA code of -// all basic blocks of function f. -// -func (f *Function) DumpTo(w io.Writer) { - fmt.Fprintf(w, "# Name: %s\n", f.FullName()) - fmt.Fprintf(w, "# Declared at %s\n", f.Prog.Files.Position(f.Pos)) - fmt.Fprintf(w, "# Type: %s\n", f.Signature) - - if f.Enclosing != nil { - fmt.Fprintf(w, "# Parent: %s\n", f.Enclosing.Name()) - } - - if f.FreeVars != nil { - io.WriteString(w, "# Free variables:\n") - for i, fv := range f.FreeVars { - fmt.Fprintf(w, "# % 3d:\t%s %s\n", i, fv.Name(), fv.Type()) - } - } - - params := f.Params - if f.Signature.Recv != nil { - fmt.Fprintf(w, "func (%s) %s(", params[0].Name(), f.Name()) - params = params[1:] - } else { - fmt.Fprintf(w, "func %s(", f.Name()) - } - for i, v := range params { - if i > 0 { - io.WriteString(w, ", ") - } - io.WriteString(w, v.Name()) - } - io.WriteString(w, "):\n") - - for _, b := range f.Blocks { - if b == nil { - // Corrupt CFG. - fmt.Fprintf(w, ".nil:\n") - continue - } - fmt.Fprintf(w, ".%s:\t\t\t\t\t\t\t P:%d S:%d\n", b.Name, len(b.Preds), len(b.Succs)) - if false { // CFG debugging - fmt.Fprintf(w, "\t# CFG: %s --> %s --> %s\n", blockNames(b.Preds), b.Name, blockNames(b.Succs)) - } - for _, instr := range b.Instrs { - io.WriteString(w, "\t") - if v, ok := instr.(Value); ok { - l := 80 // for old time's sake. - // Left-align the instruction. - if name := v.Name(); name != "" { - n, _ := fmt.Fprintf(w, "%s = ", name) - l -= n - } - n, _ := io.WriteString(w, instr.String()) - l -= n - // Right-align the type. - if t := v.Type(); t != nil { - fmt.Fprintf(w, "%*s", l-9, t) - } - } else { - io.WriteString(w, instr.String()) - } - io.WriteString(w, "\n") - } - } - fmt.Fprintf(w, "\n") -} - -// newBasicBlock adds to f a new basic block with a unique name and -// returns it. It does not automatically become the current block for -// subsequent calls to emit. -// -func (f *Function) newBasicBlock(name string) *BasicBlock { - b := &BasicBlock{ - Name: fmt.Sprintf("%d.%s", len(f.Blocks), name), - Func: f, - } - b.Succs = b.succs2[:0] - f.Blocks = append(f.Blocks, b) - return b -} diff --git a/gcc-4.8.1/libgo/go/exp/ssa/literal.go b/gcc-4.8.1/libgo/go/exp/ssa/literal.go deleted file mode 100644 index fa26c47e9..000000000 --- a/gcc-4.8.1/libgo/go/exp/ssa/literal.go +++ /dev/null @@ -1,137 +0,0 @@ -package ssa - -// This file defines the Literal SSA value type. - -import ( - "fmt" - "go/types" - "math/big" - "strconv" -) - -// newLiteral returns a new literal of the specified value and type. -// val must be valid according to the specification of Literal.Value. -// -func newLiteral(val interface{}, typ types.Type) *Literal { - // This constructor exists to provide a single place to - // insert logging/assertions during debugging. - return &Literal{typ, val} -} - -// intLiteral returns an untyped integer literal that evaluates to i. -func intLiteral(i int64) *Literal { - return newLiteral(i, types.Typ[types.UntypedInt]) -} - -// nilLiteral returns a nil literal of the specified (reference) type. -func nilLiteral(typ types.Type) *Literal { - return newLiteral(types.NilType{}, typ) -} - -func (l *Literal) Name() string { - var s string - switch x := l.Value.(type) { - case bool: - s = fmt.Sprintf("%v", l.Value) - case int64: - s = fmt.Sprintf("%d", l.Value) - case *big.Int: - s = x.String() - case *big.Rat: - s = x.FloatString(20) - case string: - if len(x) > 20 { - x = x[:17] + "..." // abbreviate - } - s = strconv.Quote(x) - case types.Complex: - r := x.Re.FloatString(20) - i := x.Im.FloatString(20) - s = fmt.Sprintf("%s+%si", r, i) - case types.NilType: - s = "nil" - default: - panic(fmt.Sprintf("unexpected literal value: %T", x)) - } - return s + ":" + l.Type_.String() -} - -func (l *Literal) Type() types.Type { - return l.Type_ -} - -// IsNil returns true if this literal represents a typed or untyped nil value. -func (l *Literal) IsNil() bool { - _, ok := l.Value.(types.NilType) - return ok -} - -// Int64 returns the numeric value of this literal truncated to fit -// a signed 64-bit integer. -// -func (l *Literal) Int64() int64 { - switch x := l.Value.(type) { - case int64: - return x - case *big.Int: - return x.Int64() - case *big.Rat: - // TODO(adonovan): fix: is this the right rounding mode? - var q big.Int - return q.Quo(x.Num(), x.Denom()).Int64() - } - panic(fmt.Sprintf("unexpected literal value: %T", l.Value)) -} - -// Uint64 returns the numeric value of this literal truncated to fit -// an unsigned 64-bit integer. -// -func (l *Literal) Uint64() uint64 { - switch x := l.Value.(type) { - case int64: - if x < 0 { - return 0 - } - return uint64(x) - case *big.Int: - return x.Uint64() - case *big.Rat: - // TODO(adonovan): fix: is this right? - var q big.Int - return q.Quo(x.Num(), x.Denom()).Uint64() - } - panic(fmt.Sprintf("unexpected literal value: %T", l.Value)) -} - -// Float64 returns the numeric value of this literal truncated to fit -// a float64. -// -func (l *Literal) Float64() float64 { - switch x := l.Value.(type) { - case int64: - return float64(x) - case *big.Int: - var r big.Rat - f, _ := r.SetInt(x).Float64() - return f - case *big.Rat: - f, _ := x.Float64() - return f - } - panic(fmt.Sprintf("unexpected literal value: %T", l.Value)) -} - -// Complex128 returns the complex value of this literal truncated to -// fit a complex128. -// -func (l *Literal) Complex128() complex128 { - switch x := l.Value.(type) { - case int64, *big.Int, *big.Rat: - return complex(l.Float64(), 0) - case types.Complex: - re64, _ := x.Re.Float64() - im64, _ := x.Im.Float64() - return complex(re64, im64) - } - panic(fmt.Sprintf("unexpected literal value: %T", l.Value)) -} diff --git a/gcc-4.8.1/libgo/go/exp/ssa/print.go b/gcc-4.8.1/libgo/go/exp/ssa/print.go deleted file mode 100644 index b8708b6ed..000000000 --- a/gcc-4.8.1/libgo/go/exp/ssa/print.go +++ /dev/null @@ -1,383 +0,0 @@ -package ssa - -// This file implements the String() methods for all Value and -// Instruction types. - -import ( - "bytes" - "fmt" - "go/ast" - "go/types" -) - -func (id Id) String() string { - if id.Pkg == nil { - return id.Name - } - return fmt.Sprintf("%s/%s", id.Pkg.Path, id.Name) -} - -// relName returns the name of v relative to i. -// In most cases, this is identical to v.Name(), but for cross-package -// references to Functions (including methods) and Globals, the -// package-qualified FullName is used instead. -// -func relName(v Value, i Instruction) string { - switch v := v.(type) { - case *Global: - if v.Pkg == i.Block().Func.Pkg { - return v.Name() - } - return v.FullName() - case *Function: - if v.Pkg == nil || v.Pkg == i.Block().Func.Pkg { - return v.Name() - } - return v.FullName() - } - return v.Name() -} - -// Value.String() -// -// This method is provided only for debugging. -// It never appears in disassembly, which uses Value.Name(). - -func (v *Literal) String() string { - return fmt.Sprintf("literal %s rep=%T", v.Name(), v.Value) -} - -func (v *Parameter) String() string { - return fmt.Sprintf("parameter %s : %s", v.Name(), v.Type()) -} - -func (v *Capture) String() string { - return fmt.Sprintf("capture %s : %s", v.Name(), v.Type()) -} - -func (v *Global) String() string { - return fmt.Sprintf("global %s : %s", v.Name(), v.Type()) -} - -func (v *Builtin) String() string { - return fmt.Sprintf("builtin %s : %s", v.Name(), v.Type()) -} - -func (r *Function) String() string { - return fmt.Sprintf("function %s : %s", r.Name(), r.Type()) -} - -// FullName returns the name of this function qualified by the -// package name, unless it is anonymous or synthetic. -// -// TODO(adonovan): move to func.go when it's submitted. -// -func (f *Function) FullName() string { - if f.Enclosing != nil || f.Pkg == nil { - return f.Name_ // anonymous or synthetic - } - return fmt.Sprintf("%s.%s", f.Pkg.ImportPath, f.Name_) -} - -// FullName returns g's package-qualified name. -func (g *Global) FullName() string { - return fmt.Sprintf("%s.%s", g.Pkg.ImportPath, g.Name_) -} - -// Instruction.String() - -func (v *Alloc) String() string { - op := "local" - if v.Heap { - op = "new" - } - return fmt.Sprintf("%s %s", op, indirectType(v.Type())) -} - -func (v *Phi) String() string { - var b bytes.Buffer - b.WriteString("phi [") - for i, edge := range v.Edges { - if i > 0 { - b.WriteString(", ") - } - // Be robust against malformed CFG. - blockname := "?" - if v.Block_ != nil && i < len(v.Block_.Preds) { - blockname = v.Block_.Preds[i].Name - } - b.WriteString(blockname) - b.WriteString(": ") - b.WriteString(relName(edge, v)) - } - b.WriteString("]") - return b.String() -} - -func printCall(v *CallCommon, prefix string, instr Instruction) string { - var b bytes.Buffer - b.WriteString(prefix) - if v.Func != nil { - b.WriteString(relName(v.Func, instr)) - } else { - name := underlyingType(v.Recv.Type()).(*types.Interface).Methods[v.Method].Name - fmt.Fprintf(&b, "invoke %s.%s [#%d]", relName(v.Recv, instr), name, v.Method) - } - b.WriteString("(") - for i, arg := range v.Args { - if i > 0 { - b.WriteString(", ") - } - b.WriteString(relName(arg, instr)) - } - if v.HasEllipsis { - b.WriteString("...") - } - b.WriteString(")") - return b.String() -} - -func (v *Call) String() string { - return printCall(&v.CallCommon, "", v) -} - -func (v *BinOp) String() string { - return fmt.Sprintf("%s %s %s", relName(v.X, v), v.Op.String(), relName(v.Y, v)) -} - -func (v *UnOp) String() string { - return fmt.Sprintf("%s%s%s", v.Op, relName(v.X, v), commaOk(v.CommaOk)) -} - -func (v *Conv) String() string { - return fmt.Sprintf("convert %s <- %s (%s)", v.Type(), v.X.Type(), relName(v.X, v)) -} - -func (v *ChangeInterface) String() string { - return fmt.Sprintf("change interface %s <- %s (%s)", v.Type(), v.X.Type(), relName(v.X, v)) -} - -func (v *MakeInterface) String() string { - return fmt.Sprintf("make interface %s <- %s (%s)", v.Type(), v.X.Type(), relName(v.X, v)) -} - -func (v *MakeClosure) String() string { - var b bytes.Buffer - fmt.Fprintf(&b, "make closure %s", relName(v.Fn, v)) - if v.Bindings != nil { - b.WriteString(" [") - for i, c := range v.Bindings { - if i > 0 { - b.WriteString(", ") - } - b.WriteString(relName(c, v)) - } - b.WriteString("]") - } - return b.String() -} - -func (v *MakeSlice) String() string { - var b bytes.Buffer - b.WriteString("make slice ") - b.WriteString(v.Type().String()) - b.WriteString(" ") - b.WriteString(relName(v.Len, v)) - b.WriteString(" ") - b.WriteString(relName(v.Cap, v)) - return b.String() -} - -func (v *Slice) String() string { - var b bytes.Buffer - b.WriteString("slice ") - b.WriteString(relName(v.X, v)) - b.WriteString("[") - if v.Low != nil { - b.WriteString(relName(v.Low, v)) - } - b.WriteString(":") - if v.High != nil { - b.WriteString(relName(v.High, v)) - } - b.WriteString("]") - return b.String() -} - -func (v *MakeMap) String() string { - res := "" - if v.Reserve != nil { - res = relName(v.Reserve, v) - } - return fmt.Sprintf("make %s %s", v.Type(), res) -} - -func (v *MakeChan) String() string { - return fmt.Sprintf("make %s %s", v.Type(), relName(v.Size, v)) -} - -func (v *FieldAddr) String() string { - fields := underlyingType(indirectType(v.X.Type())).(*types.Struct).Fields - // Be robust against a bad index. - name := "?" - if v.Field >= 0 && v.Field < len(fields) { - name = fields[v.Field].Name - } - return fmt.Sprintf("&%s.%s [#%d]", relName(v.X, v), name, v.Field) -} - -func (v *Field) String() string { - fields := underlyingType(v.X.Type()).(*types.Struct).Fields - // Be robust against a bad index. - name := "?" - if v.Field >= 0 && v.Field < len(fields) { - name = fields[v.Field].Name - } - return fmt.Sprintf("%s.%s [#%d]", relName(v.X, v), name, v.Field) -} - -func (v *IndexAddr) String() string { - return fmt.Sprintf("&%s[%s]", relName(v.X, v), relName(v.Index, v)) -} - -func (v *Index) String() string { - return fmt.Sprintf("%s[%s]", relName(v.X, v), relName(v.Index, v)) -} - -func (v *Lookup) String() string { - return fmt.Sprintf("%s[%s]%s", relName(v.X, v), relName(v.Index, v), commaOk(v.CommaOk)) -} - -func (v *Range) String() string { - return "range " + relName(v.X, v) -} - -func (v *Next) String() string { - return "next " + relName(v.Iter, v) -} - -func (v *TypeAssert) String() string { - return fmt.Sprintf("typeassert%s %s.(%s)", commaOk(v.CommaOk), relName(v.X, v), v.AssertedType) -} - -func (v *Extract) String() string { - return fmt.Sprintf("extract %s #%d", relName(v.Tuple, v), v.Index) -} - -func (s *Jump) String() string { - // Be robust against malformed CFG. - blockname := "?" - if s.Block_ != nil && len(s.Block_.Succs) == 1 { - blockname = s.Block_.Succs[0].Name - } - return fmt.Sprintf("jump %s", blockname) -} - -func (s *If) String() string { - // Be robust against malformed CFG. - tblockname, fblockname := "?", "?" - if s.Block_ != nil && len(s.Block_.Succs) == 2 { - tblockname = s.Block_.Succs[0].Name - fblockname = s.Block_.Succs[1].Name - } - return fmt.Sprintf("if %s goto %s else %s", relName(s.Cond, s), tblockname, fblockname) -} - -func (s *Go) String() string { - return printCall(&s.CallCommon, "go ", s) -} - -func (s *Ret) String() string { - var b bytes.Buffer - b.WriteString("ret") - for i, r := range s.Results { - if i == 0 { - b.WriteString(" ") - } else { - b.WriteString(", ") - } - b.WriteString(relName(r, s)) - } - return b.String() -} - -func (s *Send) String() string { - return fmt.Sprintf("send %s <- %s", relName(s.Chan, s), relName(s.X, s)) -} - -func (s *Defer) String() string { - return printCall(&s.CallCommon, "defer ", s) -} - -func (s *Select) String() string { - var b bytes.Buffer - for i, st := range s.States { - if i > 0 { - b.WriteString(", ") - } - if st.Dir == ast.RECV { - b.WriteString("<-") - b.WriteString(relName(st.Chan, s)) - } else { - b.WriteString(relName(st.Chan, s)) - b.WriteString("<-") - b.WriteString(relName(st.Send, s)) - } - } - non := "" - if !s.Blocking { - non = "non" - } - return fmt.Sprintf("select %sblocking [%s]", non, b.String()) -} - -func (s *Store) String() string { - return fmt.Sprintf("*%s = %s", relName(s.Addr, s), relName(s.Val, s)) -} - -func (s *MapUpdate) String() string { - return fmt.Sprintf("%s[%s] = %s", relName(s.Map, s), relName(s.Key, s), relName(s.Value, s)) -} - -func (p *Package) String() string { - // TODO(adonovan): prettify output. - var b bytes.Buffer - fmt.Fprintf(&b, "Package %s at %s:\n", p.ImportPath, p.Prog.Files.File(p.Pos).Name()) - - // TODO(adonovan): make order deterministic. - maxname := 0 - for name := range p.Members { - if l := len(name); l > maxname { - maxname = l - } - } - - for name, mem := range p.Members { - switch mem := mem.(type) { - case *Literal: - fmt.Fprintf(&b, " const %-*s %s\n", maxname, name, mem.Name()) - - case *Function: - fmt.Fprintf(&b, " func %-*s %s\n", maxname, name, mem.Type()) - - case *Type: - fmt.Fprintf(&b, " type %-*s %s\n", maxname, name, mem.NamedType.Underlying) - // TODO(adonovan): make order deterministic. - for name, method := range mem.Methods { - fmt.Fprintf(&b, " method %s %s\n", name, method.Signature) - } - - case *Global: - fmt.Fprintf(&b, " var %-*s %s\n", maxname, name, mem.Type()) - - } - } - return b.String() -} - -func commaOk(x bool) string { - if x { - return ",ok" - } - return "" -} diff --git a/gcc-4.8.1/libgo/go/exp/ssa/sanity.go b/gcc-4.8.1/libgo/go/exp/ssa/sanity.go deleted file mode 100644 index bbb30cfcf..000000000 --- a/gcc-4.8.1/libgo/go/exp/ssa/sanity.go +++ /dev/null @@ -1,263 +0,0 @@ -package ssa - -// An optional pass for sanity checking invariants of the SSA representation. -// Currently it checks CFG invariants but little at the instruction level. - -import ( - "bytes" - "fmt" - "io" - "os" -) - -type sanity struct { - reporter io.Writer - fn *Function - block *BasicBlock - insane bool -} - -// SanityCheck performs integrity checking of the SSA representation -// of the function fn and returns true if it was valid. Diagnostics -// are written to reporter if non-nil, os.Stderr otherwise. Some -// diagnostics are only warnings and do not imply a negative result. -// -// Sanity checking is intended to facilitate the debugging of code -// transformation passes. -// -func SanityCheck(fn *Function, reporter io.Writer) bool { - if reporter == nil { - reporter = os.Stderr - } - return (&sanity{reporter: reporter}).checkFunction(fn) -} - -// MustSanityCheck is like SanityCheck but panics instead of returning -// a negative result. -// -func MustSanityCheck(fn *Function, reporter io.Writer) { - if !SanityCheck(fn, reporter) { - panic("SanityCheck failed") - } -} - -// blockNames returns the names of the specified blocks as a -// human-readable string. -// -func blockNames(blocks []*BasicBlock) string { - var buf bytes.Buffer - for i, b := range blocks { - if i > 0 { - io.WriteString(&buf, ", ") - } - io.WriteString(&buf, b.Name) - } - return buf.String() -} - -func (s *sanity) diagnostic(prefix, format string, args ...interface{}) { - fmt.Fprintf(s.reporter, "%s: function %s", prefix, s.fn.FullName()) - if s.block != nil { - fmt.Fprintf(s.reporter, ", block %s", s.block.Name) - } - io.WriteString(s.reporter, ": ") - fmt.Fprintf(s.reporter, format, args...) - io.WriteString(s.reporter, "\n") -} - -func (s *sanity) errorf(format string, args ...interface{}) { - s.insane = true - s.diagnostic("Error", format, args...) -} - -func (s *sanity) warnf(format string, args ...interface{}) { - s.diagnostic("Warning", format, args...) -} - -// findDuplicate returns an arbitrary basic block that appeared more -// than once in blocks, or nil if all were unique. -func findDuplicate(blocks []*BasicBlock) *BasicBlock { - if len(blocks) < 2 { - return nil - } - if blocks[0] == blocks[1] { - return blocks[0] - } - // Slow path: - m := make(map[*BasicBlock]bool) - for _, b := range blocks { - if m[b] { - return b - } - m[b] = true - } - return nil -} - -func (s *sanity) checkInstr(idx int, instr Instruction) { - switch instr := instr.(type) { - case *If, *Jump, *Ret: - s.errorf("control flow instruction not at end of block") - case *Phi: - if idx == 0 { - // It suffices to apply this check to just the first phi node. - if dup := findDuplicate(s.block.Preds); dup != nil { - s.errorf("phi node in block with duplicate predecessor %s", dup.Name) - } - } else { - prev := s.block.Instrs[idx-1] - if _, ok := prev.(*Phi); !ok { - s.errorf("Phi instruction follows a non-Phi: %T", prev) - } - } - if ne, np := len(instr.Edges), len(s.block.Preds); ne != np { - s.errorf("phi node has %d edges but %d predecessors", ne, np) - } - - case *Alloc: - case *Call: - case *BinOp: - case *UnOp: - case *MakeClosure: - case *MakeChan: - case *MakeMap: - case *MakeSlice: - case *Slice: - case *Field: - case *FieldAddr: - case *IndexAddr: - case *Index: - case *Select: - case *Range: - case *TypeAssert: - case *Extract: - case *Go: - case *Defer: - case *Send: - case *Store: - case *MapUpdate: - case *Next: - case *Lookup: - case *Conv: - case *ChangeInterface: - case *MakeInterface: - // TODO(adonovan): implement checks. - default: - panic(fmt.Sprintf("Unknown instruction type: %T", instr)) - } -} - -func (s *sanity) checkFinalInstr(idx int, instr Instruction) { - switch instr.(type) { - case *If: - if nsuccs := len(s.block.Succs); nsuccs != 2 { - s.errorf("If-terminated block has %d successors; expected 2", nsuccs) - return - } - if s.block.Succs[0] == s.block.Succs[1] { - s.errorf("If-instruction has same True, False target blocks: %s", s.block.Succs[0].Name) - return - } - - case *Jump: - if nsuccs := len(s.block.Succs); nsuccs != 1 { - s.errorf("Jump-terminated block has %d successors; expected 1", nsuccs) - return - } - - case *Ret: - if nsuccs := len(s.block.Succs); nsuccs != 0 { - s.errorf("Ret-terminated block has %d successors; expected none", nsuccs) - return - } - // TODO(adonovan): check number and types of results - - default: - s.errorf("non-control flow instruction at end of block") - } -} - -func (s *sanity) checkBlock(b *BasicBlock, isEntry bool) { - s.block = b - - // Check all blocks are reachable. - // (The entry block is always implicitly reachable.) - if !isEntry && len(b.Preds) == 0 { - s.warnf("unreachable block") - if b.Instrs == nil { - // Since this block is about to be pruned, - // tolerating transient problems in it - // simplifies other optimisations. - return - } - } - - // Check predecessor and successor relations are dual. - for _, a := range b.Preds { - found := false - for _, bb := range a.Succs { - if bb == b { - found = true - break - } - } - if !found { - s.errorf("expected successor edge in predecessor %s; found only: %s", a.Name, blockNames(a.Succs)) - } - } - for _, c := range b.Succs { - found := false - for _, bb := range c.Preds { - if bb == b { - found = true - break - } - } - if !found { - s.errorf("expected predecessor edge in successor %s; found only: %s", c.Name, blockNames(c.Preds)) - } - } - - // Check each instruction is sane. - n := len(b.Instrs) - if n == 0 { - s.errorf("basic block contains no instructions") - } - for j, instr := range b.Instrs { - if b2 := instr.Block(); b2 == nil { - s.errorf("nil Block() for instruction at index %d", j) - continue - } else if b2 != b { - s.errorf("wrong Block() (%s) for instruction at index %d ", b2.Name, j) - continue - } - if j < n-1 { - s.checkInstr(j, instr) - } else { - s.checkFinalInstr(j, instr) - } - } -} - -func (s *sanity) checkFunction(fn *Function) bool { - // TODO(adonovan): check Function invariants: - // - check owning Package (if any) contains this function. - // - check params match signature - // - check locals are all !Heap - // - check transient fields are nil - // - check block labels are unique (warning) - s.fn = fn - if fn.Prog == nil { - s.errorf("nil Prog") - } - for i, b := range fn.Blocks { - if b == nil { - s.warnf("nil *BasicBlock at f.Blocks[%d]", i) - continue - } - s.checkBlock(b, i == 0) - } - s.block = nil - s.fn = nil - return !s.insane -} diff --git a/gcc-4.8.1/libgo/go/exp/ssa/ssa.go b/gcc-4.8.1/libgo/go/exp/ssa/ssa.go deleted file mode 100644 index eb0f7fc0b..000000000 --- a/gcc-4.8.1/libgo/go/exp/ssa/ssa.go +++ /dev/null @@ -1,1100 +0,0 @@ -package ssa - -// This package defines a high-level intermediate representation for -// Go programs using static single-assignment (SSA) form. - -import ( - "fmt" - "go/ast" - "go/token" - "go/types" -) - -// A Program is a partial or complete Go program converted to SSA form. -// Each Builder creates and populates a single Program during its -// lifetime. -// -// TODO(adonovan): synthetic methods for promoted methods and for -// standalone interface methods do not belong to any package. Make -// them enumerable here. -// -// TODO(adonovan): MethodSets of types other than named types -// (i.e. anon structs) are not currently accessible, nor are they -// memoized. Add a method: MethodSetForType() which looks in the -// appropriate Package (for methods of named types) or in -// Program.AnonStructMethods (for methods of anon structs). -// -type Program struct { - Files *token.FileSet // position information for the files of this Program - Packages map[string]*Package // all loaded Packages, keyed by import path - Builtins map[types.Object]*Builtin // all built-in functions, keyed by typechecker objects. -} - -// A Package is a single analyzed Go package, containing Members for -// all package-level functions, variables, constants and types it -// declares. These may be accessed directly via Members, or via the -// type-specific accessor methods Func, Type, Var and Const. -// -type Package struct { - Prog *Program // the owning program - Types *types.Package // the type checker's package object for this package. - ImportPath string // e.g. "sync/atomic" - Pos token.Pos // position of an arbitrary file in the package - Members map[string]Member // all exported and unexported members of the package - AnonFuncs []*Function // all anonymous functions in this package - Init *Function // the package's (concatenated) init function - - // The following fields are set transiently during building, - // then cleared. - files []*ast.File // the abstract syntax tree for the files of the package -} - -// A Member is a member of a Go package, implemented by *Literal, -// *Global, *Function, or *Type; they are created by package-level -// const, var, func and type declarations respectively. -// -type Member interface { - Name() string // the declared name of the package member - String() string // human-readable information about the value - Type() types.Type // the type of the package member - ImplementsMember() // dummy method to indicate the "implements" relation. -} - -// An Id identifies the name of a field of a struct type, or the name -// of a method of an interface or a named type. -// -// For exported names, i.e. those beginning with a Unicode upper-case -// letter, a simple string is unambiguous. -// -// However, a method set or struct may contain multiple unexported -// names with identical spelling that are logically distinct because -// they originate in different packages. Unexported names must -// therefore be disambiguated by their package too. -// -// The Pkg field of an Id is therefore nil iff the name is exported. -// -// This type is suitable for use as a map key because the equivalence -// relation == is consistent with identifier equality. -type Id struct { - Pkg *types.Package - Name string -} - -// A MethodSet contains all the methods whose receiver is either T or -// *T, for some named or struct type T. -// -// TODO(adonovan): the client is required to adapt T<=>*T, e.g. when -// invoking an interface method. (This could be simplified for the -// client by having distinct method sets for T and *T, with the SSA -// Builder generating wrappers as needed, but probably the client is -// able to do a better job.) Document the precise rules the client -// must follow. -// -type MethodSet map[Id]*Function - -// A Type is a Member of a Package representing the name, underlying -// type and method set of a named type declared at package scope. -// -// The method set contains only concrete methods; it is empty for -// interface types. -// -type Type struct { - NamedType *types.NamedType - Methods MethodSet -} - -// An SSA value that can be referenced by an instruction. -// -// TODO(adonovan): add methods: -// - Referrers() []*Instruction // all instructions that refer to this value. -// -type Value interface { - // Name returns the name of this value, and determines how - // this Value appears when used as an operand of an - // Instruction. - // - // This is the same as the source name for Parameters, - // Builtins, Functions, Captures, Globals and some Allocs. - // For literals, it is a representation of the literal's value - // and type. For all other Values this is the name of the - // virtual register defined by the instruction. - // - // The name of an SSA Value is not semantically significant, - // and may not even be unique within a function. - Name() string - - // If this value is an Instruction, String returns its - // disassembled form; otherwise it returns unspecified - // human-readable information about the Value, such as its - // kind, name and type. - String() string - - // Type returns the type of this value. Many instructions - // (e.g. IndexAddr) change the behaviour depending on the - // types of their operands. - // - // Documented type invariants below (e.g. "Alloc.Type() - // returns a *types.Pointer") refer to the underlying type in - // the case of NamedTypes. - Type() types.Type - - // Dummy method to indicate the "implements" relation. - ImplementsValue() -} - -// An Instruction is an SSA instruction that computes a new Value or -// has some effect. -// -// An Instruction that defines a value (e.g. BinOp) also implements -// the Value interface; an Instruction that only has an effect (e.g. Store) -// does not. -// -// TODO(adonovan): add method: -// - Operands() []Value // all Values referenced by this instruction. -// -type Instruction interface { - // String returns the disassembled form of this value. e.g. - // - // Examples of Instructions that define a Value: - // e.g. "x + y" (BinOp) - // "len([])" (Call) - // Note that the name of the Value is not printed. - // - // Examples of Instructions that do define (are) Values: - // e.g. "ret x" (Ret) - // "*y = x" (Store) - // - // (This separation is useful for some analyses which - // distinguish the operation from the value it - // defines. e.g. 'y = local int' is both an allocation of - // memory 'local int' and a definition of a pointer y.) - String() string - - // Block returns the basic block to which this instruction - // belongs. - Block() *BasicBlock - - // SetBlock sets the basic block to which this instruction - // belongs. - SetBlock(*BasicBlock) - - // Dummy method to indicate the "implements" relation. - ImplementsInstruction() -} - -// Function represents the parameters, results and code of a function -// or method. -// -// If Blocks is nil, this indicates an external function for which no -// Go source code is available. In this case, Captures and Locals -// will be nil too. Clients performing whole-program analysis must -// handle external functions specially. -// -// Functions are immutable values; they do not have addresses. -// -// Blocks[0] is the function entry point; block order is not otherwise -// semantically significant, though it may affect the readability of -// the disassembly. -// -// A nested function that refers to one or more lexically enclosing -// local variables ("free variables") has Capture parameters. Such -// functions cannot be called directly but require a value created by -// MakeClosure which, via its Bindings, supplies values for these -// parameters. Captures are always addresses. -// -// If the function is a method (Signature.Recv != nil) then the first -// element of Params is the receiver parameter. -// -// Type() returns the function's Signature. -// -type Function struct { - Name_ string - Signature *types.Signature - - Pos token.Pos // location of the definition - Enclosing *Function // enclosing function if anon; nil if global - Pkg *Package // enclosing package; nil for some synthetic methods - Prog *Program // enclosing program - Params []*Parameter - FreeVars []*Capture // free variables whose values must be supplied by closure - Locals []*Alloc - Blocks []*BasicBlock // basic blocks of the function; nil => external - - // The following fields are set transiently during building, - // then cleared. - currentBlock *BasicBlock // where to emit code - objects map[types.Object]Value // addresses of local variables - results []*Alloc // tuple of named results - syntax *funcSyntax // abstract syntax trees for Go source functions - targets *targets // linked stack of branch targets - lblocks map[*ast.Object]*lblock // labelled blocks -} - -// An SSA basic block. -// -// The final element of Instrs is always an explicit transfer of -// control (If, Jump or Ret). -// -// A block may contain no Instructions only if it is unreachable, -// i.e. Preds is nil. Empty blocks are typically pruned. -// -// BasicBlocks and their Preds/Succs relation form a (possibly cyclic) -// graph independent of the SSA Value graph. It is illegal for -// multiple edges to exist between the same pair of blocks. -// -// The order of Preds and Succs are significant (to Phi and If -// instructions, respectively). -// -type BasicBlock struct { - Name string // label; no semantic significance - Func *Function // containing function - Instrs []Instruction // instructions in order - Preds, Succs []*BasicBlock // predecessors and successors - succs2 [2]*BasicBlock // initial space for Succs. -} - -// Pure values ---------------------------------------- - -// A Capture is a pointer to a lexically enclosing local variable. -// -// The referent of a capture is an Alloc or another Capture and is -// always considered potentially escaping, so Captures are always -// addresses in the heap, and have pointer types. -// -type Capture struct { - Outer Value // the Value captured from the enclosing context. -} - -// A Parameter represents an input parameter of a function. -// -type Parameter struct { - Name_ string - Type_ types.Type -} - -// A Literal represents a literal nil, boolean, string or numeric -// (integer, fraction or complex) value. -// -// A literal's underlying Type() can be a basic type, possibly one of -// the "untyped" types. A nil literal can have any reference type: -// interface, map, channel, pointer, slice, or function---but not -// "untyped nil". -// -// All source-level constant expressions are represented by a Literal -// of equal type and value. -// -// Value holds the exact value of the literal, independent of its -// Type(), using the same representation as package go/types uses for -// constants. -// -// Example printed form: -// 42:int -// "hello":untyped string -// 3+4i:MyComplex -// -type Literal struct { - Type_ types.Type - Value interface{} -} - -// A Global is a named Value holding the address of a package-level -// variable. -// -type Global struct { - Name_ string - Type_ types.Type - Pkg *Package - - // The following fields are set transiently during building, - // then cleared. - spec *ast.ValueSpec // explained at buildGlobal -} - -// A built-in function, e.g. len. -// -// Builtins are immutable values; they do not have addresses. -// -// Type() returns an inscrutable *types.builtin. Built-in functions -// may have polymorphic or variadic types that are not expressible in -// Go's type system. -// -type Builtin struct { - Object *types.Func // canonical types.Universe object for this built-in -} - -// Value-defining instructions ---------------------------------------- - -// The Alloc instruction reserves space for a value of the given type, -// zero-initializes it, and yields its address. -// -// Alloc values are always addresses, and have pointer types, so the -// type of the allocated space is actually indirect(Type()). -// -// If Heap is false, Alloc allocates space in the function's -// activation record (frame); we refer to an Alloc(Heap=false) as a -// "local" alloc. Each local Alloc returns the same address each time -// it is executed within the same activation; the space is -// re-initialized to zero. -// -// If Heap is true, Alloc allocates space in the heap, and returns; we -// refer to an Alloc(Heap=true) as a "new" alloc. Each new Alloc -// returns a different address each time it is executed. -// -// When Alloc is applied to a channel, map or slice type, it returns -// the address of an uninitialized (nil) reference of that kind; store -// the result of MakeSlice, MakeMap or MakeChan in that location to -// instantiate these types. -// -// Example printed form: -// t0 = local int -// t1 = new int -// -type Alloc struct { - anInstruction - Name_ string - Type_ types.Type - Heap bool -} - -// Phi represents an SSA φ-node, which combines values that differ -// across incoming control-flow edges and yields a new value. Within -// a block, all φ-nodes must appear before all non-φ nodes. -// -// Example printed form: -// t2 = phi [0.start: t0, 1.if.then: t1, ...] -// -type Phi struct { - Register - Edges []Value // Edges[i] is value for Block().Preds[i] -} - -// Call represents a function or method call. -// -// The Call instruction yields the function result, if there is -// exactly one, or a tuple (empty or len>1) whose components are -// accessed via Extract. -// -// See CallCommon for generic function call documentation. -// -// Example printed form: -// t2 = println(t0, t1) -// t4 = t3() -// t7 = invoke t5.Println(...t6) -// -type Call struct { - Register - CallCommon -} - -// BinOp yields the result of binary operation X Op Y. -// -// Example printed form: -// t1 = t0 + 1:int -// -type BinOp struct { - Register - // One of: - // ADD SUB MUL QUO REM + - * / % - // AND OR XOR SHL SHR AND_NOT & | ^ << >> &~ - // EQL LSS GTR NEQ LEQ GEQ == != < <= < >= - Op token.Token - X, Y Value -} - -// UnOp yields the result of Op X. -// ARROW is channel receive. -// MUL is pointer indirection (load). -// -// If CommaOk and Op=ARROW, the result is a 2-tuple of the value above -// and a boolean indicating the success of the receive. The -// components of the tuple are accessed using Extract. -// -// Example printed form: -// t0 = *x -// t2 = <-t1,ok -// -type UnOp struct { - Register - Op token.Token // One of: NOT SUB ARROW MUL XOR ! - <- * ^ - X Value - CommaOk bool -} - -// Conv yields the conversion of X to type Type(). -// -// A conversion is one of the following kinds. The behaviour of the -// conversion operator may depend on both Type() and X.Type(), as well -// as the dynamic value. -// -// A '+' indicates that a dynamic representation change may occur. -// A '-' indicates that the conversion is a value-preserving change -// to types only. -// -// 1. implicit conversions (arising from assignability rules): -// - adding/removing a name, same underlying types. -// - channel type restriction, possibly adding/removing a name. -// 2. explicit conversions (in addition to the above): -// - changing a name, same underlying types. -// - between pointers to identical base types. -// + conversions between real numeric types. -// + conversions between complex numeric types. -// + integer/[]byte/[]rune -> string. -// + string -> []byte/[]rune. -// -// TODO(adonovan): split into two cases: -// - rename value (ChangeType) -// + value to type with different representation (Conv) -// -// Conversions of untyped string/number/bool constants to a specific -// representation are eliminated during SSA construction. -// -// Example printed form: -// t1 = convert interface{} <- int (t0) -// -type Conv struct { - Register - X Value -} - -// ChangeInterface constructs a value of one interface type from a -// value of another interface type known to be assignable to it. -// -// Example printed form: -// t1 = change interface interface{} <- I (t0) -// -type ChangeInterface struct { - Register - X Value -} - -// MakeInterface constructs an instance of an interface type from a -// value and its method-set. -// -// To construct the zero value of an interface type T, use: -// &Literal{types.nilType{}, T} -// -// Example printed form: -// t1 = make interface interface{} <- int (42:int) -// -type MakeInterface struct { - Register - X Value - Methods MethodSet // method set of (non-interface) X iff converting to interface -} - -// A MakeClosure instruction yields an anonymous function value whose -// code is Fn and whose lexical capture slots are populated by Bindings. -// -// By construction, all captured variables are addresses of variables -// allocated with 'new', i.e. Alloc(Heap=true). -// -// Type() returns a *types.Signature. -// -// Example printed form: -// t0 = make closure anon@1.2 [x y z] -// -type MakeClosure struct { - Register - Fn *Function - Bindings []Value // values for each free variable in Fn.FreeVars -} - -// The MakeMap instruction creates a new hash-table-based map object -// and yields a value of kind map. -// -// Type() returns a *types.Map. -// -// Example printed form: -// t1 = make map[string]int t0 -// -type MakeMap struct { - Register - Reserve Value // initial space reservation; nil => default -} - -// The MakeChan instruction creates a new channel object and yields a -// value of kind chan. -// -// Type() returns a *types.Chan. -// -// Example printed form: -// t0 = make chan int 0 -// -type MakeChan struct { - Register - Size Value // int; size of buffer; zero => synchronous. -} - -// MakeSlice yields a slice of length Len backed by a newly allocated -// array of length Cap. -// -// Both Len and Cap must be non-nil Values of integer type. -// -// (Alloc(types.Array) followed by Slice will not suffice because -// Alloc can only create arrays of statically known length.) -// -// Type() returns a *types.Slice. -// -// Example printed form: -// t1 = make slice []string 1:int t0 -// -type MakeSlice struct { - Register - Len Value - Cap Value -} - -// Slice yields a slice of an existing string, slice or *array X -// between optional integer bounds Low and High. -// -// Type() returns string if the type of X was string, otherwise a -// *types.Slice with the same element type as X. -// -// Example printed form: -// t1 = slice t0[1:] -// -type Slice struct { - Register - X Value // slice, string, or *array - Low, High Value // either may be nil -} - -// FieldAddr yields the address of Field of *struct X. -// -// The field is identified by its index within the field list of the -// struct type of X. -// -// Type() returns a *types.Pointer. -// -// Example printed form: -// t1 = &t0.name [#1] -// -type FieldAddr struct { - Register - X Value // *struct - Field int // index into X.Type().(*types.Struct).Fields -} - -// Field yields the Field of struct X. -// -// The field is identified by its index within the field list of the -// struct type of X; by using numeric indices we avoid ambiguity of -// package-local identifiers and permit compact representations. -// -// Example printed form: -// t1 = t0.name [#1] -// -type Field struct { - Register - X Value // struct - Field int // index into X.Type().(*types.Struct).Fields -} - -// IndexAddr yields the address of the element at index Index of -// collection X. Index is an integer expression. -// -// The elements of maps and strings are not addressable; use Lookup or -// MapUpdate instead. -// -// Type() returns a *types.Pointer. -// -// Example printed form: -// t2 = &t0[t1] -// -type IndexAddr struct { - Register - X Value // slice or *array, - Index Value // numeric index -} - -// Index yields element Index of array X. -// -// TODO(adonovan): permit X to have type slice. -// Currently this requires IndexAddr followed by Load. -// -// Example printed form: -// t2 = t0[t1] -// -type Index struct { - Register - X Value // array - Index Value // integer index -} - -// Lookup yields element Index of collection X, a map or string. -// Index is an integer expression if X is a string or the appropriate -// key type if X is a map. -// -// If CommaOk, the result is a 2-tuple of the value above and a -// boolean indicating the result of a map membership test for the key. -// The components of the tuple are accessed using Extract. -// -// Example printed form: -// t2 = t0[t1] -// t5 = t3[t4],ok -// -type Lookup struct { - Register - X Value // string or map - Index Value // numeric or key-typed index - CommaOk bool // return a value,ok pair -} - -// SelectState is a helper for Select. -// It represents one goal state and its corresponding communication. -// -type SelectState struct { - Dir ast.ChanDir // direction of case - Chan Value // channel to use (for send or receive) - Send Value // value to send (for send) -} - -// Select tests whether (or blocks until) one or more of the specified -// sent or received states is entered. -// -// It returns a triple (index int, recv ?, recvOk bool) whose -// components, described below, must be accessed via the Extract -// instruction. -// -// If Blocking, select waits until exactly one state holds, i.e. a -// channel becomes ready for the designated operation of sending or -// receiving; select chooses one among the ready states -// pseudorandomly, performs the send or receive operation, and sets -// 'index' to the index of the chosen channel. -// -// If !Blocking, select doesn't block if no states hold; instead it -// returns immediately with index equal to -1. -// -// If the chosen channel was used for a receive, 'recv' is set to the -// received value; Otherwise it is unspecified. recv has no useful -// type since it is conceptually the union of all possible received -// values. -// -// The third component of the triple, recvOk, is a boolean whose value -// is true iff the selected operation was a receive and the receive -// successfully yielded a value. -// -// Example printed form: -// t3 = select nonblocking [<-t0, t1<-t2, ...] -// t4 = select blocking [] -// -type Select struct { - Register - States []SelectState - Blocking bool -} - -// Range yields an iterator over the domain and range of X. -// Elements are accessed via Next. -// -// Type() returns a *types.Result (tuple type). -// -// Example printed form: -// t0 = range "hello":string -// -type Range struct { - Register - X Value // array, *array, slice, string, map or chan -} - -// Next reads and advances the iterator Iter and returns a 3-tuple -// value (ok, k, v). If the iterator is not exhausted, ok is true and -// k and v are the next elements of the domain and range, -// respectively. Otherwise ok is false and k and v are undefined. -// -// For channel iterators, k is the received value and v is always -// undefined. -// -// Components of the tuple are accessed using Extract. -// -// Type() returns a *types.Result (tuple type). -// -// Example printed form: -// t1 = next t0 -// -type Next struct { - Register - Iter Value -} - -// TypeAssert tests whether interface value X has type -// AssertedType. -// -// If CommaOk: on success it returns a pair (v, true) where v is a -// copy of value X; on failure it returns (z, false) where z is the -// zero value of that type. The components of the pair must be -// accessed using the Extract instruction. -// -// If !CommaOk, on success it returns just the single value v; on -// failure it panics. -// -// Type() reflects the actual type of the result, possibly a pair -// (types.Result); AssertedType is the asserted type. -// -// Example printed form: -// t1 = typeassert t0.(int) -// t3 = typeassert,ok t2.(T) -// -type TypeAssert struct { - Register - X Value - AssertedType types.Type - CommaOk bool -} - -// Extract yields component Index of Tuple. -// -// This is used to access the results of instructions with multiple -// return values, such as Call, TypeAssert, Next, UnOp(ARROW) and -// IndexExpr(Map). -// -// Example printed form: -// t1 = extract t0 #1 -// -type Extract struct { - Register - Tuple Value - Index int -} - -// Instructions executed for effect. They do not yield a value. -------------------- - -// Jump transfers control to the sole successor of its owning block. -// -// A Jump instruction must be the last instruction of its containing -// BasicBlock. -// -// Example printed form: -// jump done -// -type Jump struct { - anInstruction -} - -// The If instruction transfers control to one of the two successors -// of its owning block, depending on the boolean Cond: the first if -// true, the second if false. -// -// An If instruction must be the last instruction of its containing -// BasicBlock. -// -// Example printed form: -// if t0 goto done else body -// -type If struct { - anInstruction - Cond Value -} - -// Ret returns values and control back to the calling function. -// -// len(Results) is always equal to the number of results in the -// function's signature. A source-level 'return' statement with no -// operands in a multiple-return value function is desugared to make -// the results explicit. -// -// If len(Results) > 1, Ret returns a tuple value with the specified -// components which the caller must access using Extract instructions. -// -// There is no instruction to return a ready-made tuple like those -// returned by a "value,ok"-mode TypeAssert, Lookup or UnOp(ARROW) or -// a tail-call to a function with multiple result parameters. -// TODO(adonovan): consider defining one; but: dis- and re-assembling -// the tuple is unavoidable if assignability conversions are required -// on the components. -// -// Ret must be the last instruction of its containing BasicBlock. -// Such a block has no successors. -// -// Example printed form: -// ret -// ret nil:I, 2:int -// -type Ret struct { - anInstruction - Results []Value -} - -// Go creates a new goroutine and calls the specified function -// within it. -// -// See CallCommon for generic function call documentation. -// -// Example printed form: -// go println(t0, t1) -// go t3() -// go invoke t5.Println(...t6) -// -type Go struct { - anInstruction - CallCommon -} - -// Defer pushes the specified call onto a stack of functions -// to be called immediately prior to returning from the -// current function. -// -// See CallCommon for generic function call documentation. -// -// Example printed form: -// defer println(t0, t1) -// defer t3() -// defer invoke t5.Println(...t6) -// -type Defer struct { - anInstruction - CallCommon -} - -// Send sends X on channel Chan. -// -// Example printed form: -// send t0 <- t1 -// -type Send struct { - anInstruction - Chan, X Value -} - -// Store stores Val at address Addr. -// Stores can be of arbitrary types. -// -// Example printed form: -// *x = y -// -type Store struct { - anInstruction - Addr Value - Val Value -} - -// MapUpdate updates the association of Map[Key] to Value. -// -// Example printed form: -// t0[t1] = t2 -// -type MapUpdate struct { - anInstruction - Map Value - Key Value - Value Value -} - -// Embeddable mix-ins used for common parts of other structs. -------------------- - -// Register is a mix-in embedded by all SSA values that are also -// instructions, i.e. virtual registers, and provides implementations -// of the Value interface's Name() and Type() methods: the name is -// simply a numbered register (e.g. "t0") and the type is the Type_ -// field. -// -// Temporary names are automatically assigned to each Register on -// completion of building a function in SSA form. -// -// Clients must not assume that the 'id' value (and the Name() derived -// from it) is unique within a function. As always in this API, -// semantics are determined only by identity; names exist only to -// facilitate debugging. -// -type Register struct { - anInstruction - num int // "name" of virtual register, e.g. "t0". Not guaranteed unique. - Type_ types.Type // type of virtual register -} - -// AnInstruction is a mix-in embedded by all Instructions. -// It provides the implementations of the Block and SetBlock methods. -type anInstruction struct { - Block_ *BasicBlock // the basic block of this instruction -} - -// CallCommon is a mix-in embedded by Go, Defer and Call to hold the -// common parts of a function or method call. -// -// Each CallCommon exists in one of two modes, function call and -// interface method invocation, or "call" and "invoke" for short. -// -// 1. "call" mode: when Recv is nil, a CallCommon represents an -// ordinary function call of the value in Func. -// -// In the common case in which Func is a *Function, this indicates a -// statically dispatched call to a package-level function, an -// anonymous function, or a method of a named type. Also statically -// dispatched, but less common, Func may be a *MakeClosure, indicating -// an immediately applied function literal with free variables. Any -// other Value of Func indicates a dynamically dispatched function -// call. -// -// Args contains the arguments to the call. If Func is a method, -// Args[0] contains the receiver parameter. Recv and Method are not -// used in this mode. -// -// Example printed form: -// t2 = println(t0, t1) -// go t3() -// defer t5(...t6) -// -// 2. "invoke" mode: when Recv is non-nil, a CallCommon represents a -// dynamically dispatched call to an interface method. In this -// mode, Recv is the interface value and Method is the index of the -// method within the interface type of the receiver. -// -// Recv is implicitly supplied to the concrete method implementation -// as the receiver parameter; in other words, Args[0] holds not the -// receiver but the first true argument. Func is not used in this -// mode. -// -// Example printed form: -// t1 = invoke t0.String() -// go invoke t3.Run(t2) -// defer invoke t4.Handle(...t5) -// -// In both modes, HasEllipsis is true iff the last element of Args is -// a slice value containing zero or more arguments to a variadic -// function. (This is not semantically significant since the type of -// the called function is sufficient to determine this, but it aids -// readability of the printed form.) -// -type CallCommon struct { - Recv Value // receiver, iff interface method invocation - Method int // index of interface method within Recv.Type().(*types.Interface).Methods - Func Value // target of call, iff function call - Args []Value // actual parameters, including receiver in invoke mode - HasEllipsis bool // true iff last Args is a slice (needed?) - Pos token.Pos // position of call expression -} - -func (v *Builtin) Type() types.Type { return v.Object.GetType() } -func (v *Builtin) Name() string { return v.Object.GetName() } - -func (v *Capture) Type() types.Type { return v.Outer.Type() } -func (v *Capture) Name() string { return v.Outer.Name() } - -func (v *Global) Type() types.Type { return v.Type_ } -func (v *Global) Name() string { return v.Name_ } - -func (v *Function) Name() string { return v.Name_ } -func (v *Function) Type() types.Type { return v.Signature } - -func (v *Parameter) Type() types.Type { return v.Type_ } -func (v *Parameter) Name() string { return v.Name_ } - -func (v *Alloc) Type() types.Type { return v.Type_ } -func (v *Alloc) Name() string { return v.Name_ } - -func (v *Register) Type() types.Type { return v.Type_ } -func (v *Register) setType(typ types.Type) { v.Type_ = typ } -func (v *Register) Name() string { return fmt.Sprintf("t%d", v.num) } -func (v *Register) setNum(num int) { v.num = num } - -func (v *anInstruction) Block() *BasicBlock { return v.Block_ } -func (v *anInstruction) SetBlock(block *BasicBlock) { v.Block_ = block } - -func (ms *Type) Type() types.Type { return ms.NamedType } -func (ms *Type) String() string { return ms.Name() } -func (ms *Type) Name() string { return ms.NamedType.Obj.Name } - -func (p *Package) Name() string { return p.Types.Name } - -// Func returns the package-level function of the specified name, -// or nil if not found. -// -func (p *Package) Func(name string) (f *Function) { - f, _ = p.Members[name].(*Function) - return -} - -// Var returns the package-level variable of the specified name, -// or nil if not found. -// -func (p *Package) Var(name string) (g *Global) { - g, _ = p.Members[name].(*Global) - return -} - -// Const returns the package-level constant of the specified name, -// or nil if not found. -// -func (p *Package) Const(name string) (l *Literal) { - l, _ = p.Members[name].(*Literal) - return -} - -// Type returns the package-level type of the specified name, -// or nil if not found. -// -func (p *Package) Type(name string) (t *Type) { - t, _ = p.Members[name].(*Type) - return -} - -// "Implements" relation boilerplate. -// Don't try to factor this using promotion and mix-ins: the long-hand -// form serves as better documentation, including in godoc. - -func (*Alloc) ImplementsValue() {} -func (*BinOp) ImplementsValue() {} -func (*Builtin) ImplementsValue() {} -func (*Call) ImplementsValue() {} -func (*Capture) ImplementsValue() {} -func (*ChangeInterface) ImplementsValue() {} -func (*Conv) ImplementsValue() {} -func (*Extract) ImplementsValue() {} -func (*Field) ImplementsValue() {} -func (*FieldAddr) ImplementsValue() {} -func (*Function) ImplementsValue() {} -func (*Global) ImplementsValue() {} -func (*Index) ImplementsValue() {} -func (*IndexAddr) ImplementsValue() {} -func (*Literal) ImplementsValue() {} -func (*Lookup) ImplementsValue() {} -func (*MakeChan) ImplementsValue() {} -func (*MakeClosure) ImplementsValue() {} -func (*MakeInterface) ImplementsValue() {} -func (*MakeMap) ImplementsValue() {} -func (*MakeSlice) ImplementsValue() {} -func (*Next) ImplementsValue() {} -func (*Parameter) ImplementsValue() {} -func (*Phi) ImplementsValue() {} -func (*Range) ImplementsValue() {} -func (*Select) ImplementsValue() {} -func (*Slice) ImplementsValue() {} -func (*TypeAssert) ImplementsValue() {} -func (*UnOp) ImplementsValue() {} - -func (*Function) ImplementsMember() {} -func (*Global) ImplementsMember() {} -func (*Literal) ImplementsMember() {} -func (*Type) ImplementsMember() {} - -func (*Alloc) ImplementsInstruction() {} -func (*BinOp) ImplementsInstruction() {} -func (*Call) ImplementsInstruction() {} -func (*ChangeInterface) ImplementsInstruction() {} -func (*Conv) ImplementsInstruction() {} -func (*Defer) ImplementsInstruction() {} -func (*Extract) ImplementsInstruction() {} -func (*Field) ImplementsInstruction() {} -func (*FieldAddr) ImplementsInstruction() {} -func (*Go) ImplementsInstruction() {} -func (*If) ImplementsInstruction() {} -func (*Index) ImplementsInstruction() {} -func (*IndexAddr) ImplementsInstruction() {} -func (*Jump) ImplementsInstruction() {} -func (*Lookup) ImplementsInstruction() {} -func (*MakeChan) ImplementsInstruction() {} -func (*MakeClosure) ImplementsInstruction() {} -func (*MakeInterface) ImplementsInstruction() {} -func (*MakeMap) ImplementsInstruction() {} -func (*MakeSlice) ImplementsInstruction() {} -func (*MapUpdate) ImplementsInstruction() {} -func (*Next) ImplementsInstruction() {} -func (*Phi) ImplementsInstruction() {} -func (*Range) ImplementsInstruction() {} -func (*Ret) ImplementsInstruction() {} -func (*Select) ImplementsInstruction() {} -func (*Send) ImplementsInstruction() {} -func (*Slice) ImplementsInstruction() {} -func (*Store) ImplementsInstruction() {} -func (*TypeAssert) ImplementsInstruction() {} -func (*UnOp) ImplementsInstruction() {} diff --git a/gcc-4.8.1/libgo/go/exp/ssa/util.go b/gcc-4.8.1/libgo/go/exp/ssa/util.go deleted file mode 100644 index 0d2ebde26..000000000 --- a/gcc-4.8.1/libgo/go/exp/ssa/util.go +++ /dev/null @@ -1,172 +0,0 @@ -package ssa - -// This file defines a number of miscellaneous utility functions. - -import ( - "fmt" - "go/ast" - "go/types" -) - -func unreachable() { - panic("unreachable") -} - -//// AST utilities - -// noparens returns e with any enclosing parentheses stripped. -func noparens(e ast.Expr) ast.Expr { - for { - p, ok := e.(*ast.ParenExpr) - if !ok { - break - } - e = p.X - } - return e -} - -// isBlankIdent returns true iff e is an Ident with name "_". -// They have no associated types.Object, and thus no type. -// -// TODO(gri): consider making typechecker not treat them differently. -// It's one less thing for clients like us to worry about. -// -func isBlankIdent(e ast.Expr) bool { - id, ok := e.(*ast.Ident) - return ok && id.Name == "_" -} - -//// Type utilities. Some of these belong in go/types. - -// underlyingType returns the underlying type of typ. -// TODO(gri): this is a copy of go/types.underlying; export that function. -// -func underlyingType(typ types.Type) types.Type { - if typ, ok := typ.(*types.NamedType); ok { - return typ.Underlying // underlying types are never NamedTypes - } - if typ == nil { - panic("underlyingType(nil)") - } - return typ -} - -// isPointer returns true for types whose underlying type is a pointer. -func isPointer(typ types.Type) bool { - if nt, ok := typ.(*types.NamedType); ok { - typ = nt.Underlying - } - _, ok := typ.(*types.Pointer) - return ok -} - -// pointer(typ) returns the type that is a pointer to typ. -func pointer(typ types.Type) *types.Pointer { - return &types.Pointer{Base: typ} -} - -// indirect(typ) assumes that typ is a pointer type, -// or named alias thereof, and returns its base type. -// Panic ensures if it is not a pointer. -// -func indirectType(ptr types.Type) types.Type { - if v, ok := underlyingType(ptr).(*types.Pointer); ok { - return v.Base - } - // When debugging it is convenient to comment out this line - // and let it continue to print the (illegal) SSA form. - panic("indirect() of non-pointer type: " + ptr.String()) - return nil -} - -// deref returns a pointer's base type; otherwise it returns typ. -func deref(typ types.Type) types.Type { - if typ, ok := underlyingType(typ).(*types.Pointer); ok { - return typ.Base - } - return typ -} - -// methodIndex returns the method (and its index) named id within the -// method table methods of named or interface type typ. If not found, -// panic ensues. -// -func methodIndex(typ types.Type, methods []*types.Method, id Id) (i int, m *types.Method) { - for i, m = range methods { - if IdFromQualifiedName(m.QualifiedName) == id { - return - } - } - panic(fmt.Sprint("method not found: ", id, " in interface ", typ)) -} - -// objKind returns the syntactic category of the named entity denoted by obj. -func objKind(obj types.Object) ast.ObjKind { - switch obj.(type) { - case *types.Package: - return ast.Pkg - case *types.TypeName: - return ast.Typ - case *types.Const: - return ast.Con - case *types.Var: - return ast.Var - case *types.Func: - return ast.Fun - } - panic(fmt.Sprintf("unexpected Object type: %T", obj)) -} - -// DefaultType returns the default "typed" type for an "untyped" type; -// it returns the incoming type for all other types. If there is no -// corresponding untyped type, the result is types.Typ[types.Invalid]. -// -// Exported to exp/ssa/interp. -// -// TODO(gri): this is a copy of go/types.defaultType; export that function. -// -func DefaultType(typ types.Type) types.Type { - if t, ok := typ.(*types.Basic); ok { - k := types.Invalid - switch t.Kind { - // case UntypedNil: - // There is no default type for nil. For a good error message, - // catch this case before calling this function. - case types.UntypedBool: - k = types.Bool - case types.UntypedInt: - k = types.Int - case types.UntypedRune: - k = types.Rune - case types.UntypedFloat: - k = types.Float64 - case types.UntypedComplex: - k = types.Complex128 - case types.UntypedString: - k = types.String - } - typ = types.Typ[k] - } - return typ -} - -// makeId returns the Id (name, pkg) if the name is exported or -// (name, nil) otherwise. -// -func makeId(name string, pkg *types.Package) (id Id) { - id.Name = name - if !ast.IsExported(name) { - id.Pkg = pkg - } - return -} - -// IdFromQualifiedName returns the Id (qn.Name, qn.Pkg) if qn is an -// exported name or (qn.Name, nil) otherwise. -// -// Exported to exp/ssa/interp. -// -func IdFromQualifiedName(qn types.QualifiedName) Id { - return makeId(qn.Name, qn.Pkg) -} |