Home | History | Annotate | Download | only in ssa
      1 // Copyright 2015 The Go Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style
      3 // license that can be found in the LICENSE file.
      4 
      5 package ssa
      6 
      7 import (
      8 	"cmd/compile/internal/types"
      9 	"cmd/internal/src"
     10 	"fmt"
     11 	"math"
     12 	"sort"
     13 	"strings"
     14 )
     15 
     16 // A Value represents a value in the SSA representation of the program.
     17 // The ID and Type fields must not be modified. The remainder may be modified
     18 // if they preserve the value of the Value (e.g. changing a (mul 2 x) to an (add x x)).
     19 type Value struct {
     20 	// A unique identifier for the value. For performance we allocate these IDs
     21 	// densely starting at 1.  There is no guarantee that there won't be occasional holes, though.
     22 	ID ID
     23 
     24 	// The operation that computes this value. See op.go.
     25 	Op Op
     26 
     27 	// The type of this value. Normally this will be a Go type, but there
     28 	// are a few other pseudo-types, see type.go.
     29 	Type *types.Type
     30 
     31 	// Auxiliary info for this value. The type of this information depends on the opcode and type.
     32 	// AuxInt is used for integer values, Aux is used for other values.
     33 	// Floats are stored in AuxInt using math.Float64bits(f).
     34 	AuxInt int64
     35 	Aux    interface{}
     36 
     37 	// Arguments of this value
     38 	Args []*Value
     39 
     40 	// Containing basic block
     41 	Block *Block
     42 
     43 	// Source position
     44 	Pos src.XPos
     45 
     46 	// Use count. Each appearance in Value.Args and Block.Control counts once.
     47 	Uses int32
     48 
     49 	// Storage for the first three args
     50 	argstorage [3]*Value
     51 }
     52 
     53 // Examples:
     54 // Opcode          aux   args
     55 //  OpAdd          nil      2
     56 //  OpConst     string      0    string constant
     57 //  OpConst      int64      0    int64 constant
     58 //  OpAddcq      int64      1    amd64 op: v = arg[0] + constant
     59 
     60 // short form print. Just v#.
     61 func (v *Value) String() string {
     62 	if v == nil {
     63 		return "nil" // should never happen, but not panicking helps with debugging
     64 	}
     65 	return fmt.Sprintf("v%d", v.ID)
     66 }
     67 
     68 func (v *Value) AuxInt8() int8 {
     69 	if opcodeTable[v.Op].auxType != auxInt8 {
     70 		v.Fatalf("op %s doesn't have an int8 aux field", v.Op)
     71 	}
     72 	return int8(v.AuxInt)
     73 }
     74 
     75 func (v *Value) AuxInt16() int16 {
     76 	if opcodeTable[v.Op].auxType != auxInt16 {
     77 		v.Fatalf("op %s doesn't have an int16 aux field", v.Op)
     78 	}
     79 	return int16(v.AuxInt)
     80 }
     81 
     82 func (v *Value) AuxInt32() int32 {
     83 	if opcodeTable[v.Op].auxType != auxInt32 {
     84 		v.Fatalf("op %s doesn't have an int32 aux field", v.Op)
     85 	}
     86 	return int32(v.AuxInt)
     87 }
     88 
     89 func (v *Value) AuxFloat() float64 {
     90 	if opcodeTable[v.Op].auxType != auxFloat32 && opcodeTable[v.Op].auxType != auxFloat64 {
     91 		v.Fatalf("op %s doesn't have a float aux field", v.Op)
     92 	}
     93 	return math.Float64frombits(uint64(v.AuxInt))
     94 }
     95 func (v *Value) AuxValAndOff() ValAndOff {
     96 	if opcodeTable[v.Op].auxType != auxSymValAndOff {
     97 		v.Fatalf("op %s doesn't have a ValAndOff aux field", v.Op)
     98 	}
     99 	return ValAndOff(v.AuxInt)
    100 }
    101 
    102 // long form print.  v# = opcode <type> [aux] args [: reg] (names)
    103 func (v *Value) LongString() string {
    104 	s := fmt.Sprintf("v%d = %s", v.ID, v.Op)
    105 	s += " <" + v.Type.String() + ">"
    106 	s += v.auxString()
    107 	for _, a := range v.Args {
    108 		s += fmt.Sprintf(" %v", a)
    109 	}
    110 	r := v.Block.Func.RegAlloc
    111 	if int(v.ID) < len(r) && r[v.ID] != nil {
    112 		s += " : " + r[v.ID].String()
    113 	}
    114 	var names []string
    115 	for name, values := range v.Block.Func.NamedValues {
    116 		for _, value := range values {
    117 			if value == v {
    118 				names = append(names, name.String())
    119 				break // drop duplicates.
    120 			}
    121 		}
    122 	}
    123 	if len(names) != 0 {
    124 		sort.Strings(names) // Otherwise a source of variation in debugging output.
    125 		s += " (" + strings.Join(names, ", ") + ")"
    126 	}
    127 	return s
    128 }
    129 
    130 func (v *Value) auxString() string {
    131 	switch opcodeTable[v.Op].auxType {
    132 	case auxBool:
    133 		if v.AuxInt == 0 {
    134 			return " [false]"
    135 		} else {
    136 			return " [true]"
    137 		}
    138 	case auxInt8:
    139 		return fmt.Sprintf(" [%d]", v.AuxInt8())
    140 	case auxInt16:
    141 		return fmt.Sprintf(" [%d]", v.AuxInt16())
    142 	case auxInt32:
    143 		return fmt.Sprintf(" [%d]", v.AuxInt32())
    144 	case auxInt64, auxInt128:
    145 		return fmt.Sprintf(" [%d]", v.AuxInt)
    146 	case auxFloat32, auxFloat64:
    147 		return fmt.Sprintf(" [%g]", v.AuxFloat())
    148 	case auxString:
    149 		return fmt.Sprintf(" {%q}", v.Aux)
    150 	case auxSym, auxTyp:
    151 		if v.Aux != nil {
    152 			return fmt.Sprintf(" {%v}", v.Aux)
    153 		}
    154 	case auxSymOff, auxSymInt32, auxTypSize:
    155 		s := ""
    156 		if v.Aux != nil {
    157 			s = fmt.Sprintf(" {%v}", v.Aux)
    158 		}
    159 		if v.AuxInt != 0 {
    160 			s += fmt.Sprintf(" [%v]", v.AuxInt)
    161 		}
    162 		return s
    163 	case auxSymValAndOff:
    164 		s := ""
    165 		if v.Aux != nil {
    166 			s = fmt.Sprintf(" {%v}", v.Aux)
    167 		}
    168 		return s + fmt.Sprintf(" [%s]", v.AuxValAndOff())
    169 	}
    170 	return ""
    171 }
    172 
    173 func (v *Value) AddArg(w *Value) {
    174 	if v.Args == nil {
    175 		v.resetArgs() // use argstorage
    176 	}
    177 	v.Args = append(v.Args, w)
    178 	w.Uses++
    179 }
    180 func (v *Value) AddArgs(a ...*Value) {
    181 	if v.Args == nil {
    182 		v.resetArgs() // use argstorage
    183 	}
    184 	v.Args = append(v.Args, a...)
    185 	for _, x := range a {
    186 		x.Uses++
    187 	}
    188 }
    189 func (v *Value) SetArg(i int, w *Value) {
    190 	v.Args[i].Uses--
    191 	v.Args[i] = w
    192 	w.Uses++
    193 }
    194 func (v *Value) RemoveArg(i int) {
    195 	v.Args[i].Uses--
    196 	copy(v.Args[i:], v.Args[i+1:])
    197 	v.Args[len(v.Args)-1] = nil // aid GC
    198 	v.Args = v.Args[:len(v.Args)-1]
    199 }
    200 func (v *Value) SetArgs1(a *Value) {
    201 	v.resetArgs()
    202 	v.AddArg(a)
    203 }
    204 func (v *Value) SetArgs2(a *Value, b *Value) {
    205 	v.resetArgs()
    206 	v.AddArg(a)
    207 	v.AddArg(b)
    208 }
    209 
    210 func (v *Value) resetArgs() {
    211 	for _, a := range v.Args {
    212 		a.Uses--
    213 	}
    214 	v.argstorage[0] = nil
    215 	v.argstorage[1] = nil
    216 	v.argstorage[2] = nil
    217 	v.Args = v.argstorage[:0]
    218 }
    219 
    220 func (v *Value) reset(op Op) {
    221 	v.Op = op
    222 	v.resetArgs()
    223 	v.AuxInt = 0
    224 	v.Aux = nil
    225 }
    226 
    227 // copyInto makes a new value identical to v and adds it to the end of b.
    228 func (v *Value) copyInto(b *Block) *Value {
    229 	c := b.NewValue0(v.Pos, v.Op, v.Type) // Lose the position, this causes line number churn otherwise.
    230 	c.Aux = v.Aux
    231 	c.AuxInt = v.AuxInt
    232 	c.AddArgs(v.Args...)
    233 	for _, a := range v.Args {
    234 		if a.Type.IsMemory() {
    235 			v.Fatalf("can't move a value with a memory arg %s", v.LongString())
    236 		}
    237 	}
    238 	return c
    239 }
    240 
    241 // copyIntoNoXPos makes a new value identical to v and adds it to the end of b.
    242 // The copied value receives no source code position to avoid confusing changes
    243 // in debugger information (the intended user is the register allocator).
    244 func (v *Value) copyIntoNoXPos(b *Block) *Value {
    245 	return v.copyIntoWithXPos(b, src.NoXPos)
    246 }
    247 
    248 // copyIntoWithXPos makes a new value identical to v and adds it to the end of b.
    249 // The supplied position is used as the position of the new value.
    250 func (v *Value) copyIntoWithXPos(b *Block, pos src.XPos) *Value {
    251 	c := b.NewValue0(pos, v.Op, v.Type)
    252 	c.Aux = v.Aux
    253 	c.AuxInt = v.AuxInt
    254 	c.AddArgs(v.Args...)
    255 	for _, a := range v.Args {
    256 		if a.Type.IsMemory() {
    257 			v.Fatalf("can't move a value with a memory arg %s", v.LongString())
    258 		}
    259 	}
    260 	return c
    261 }
    262 
    263 func (v *Value) Logf(msg string, args ...interface{}) { v.Block.Logf(msg, args...) }
    264 func (v *Value) Log() bool                            { return v.Block.Log() }
    265 func (v *Value) Fatalf(msg string, args ...interface{}) {
    266 	v.Block.Func.fe.Fatalf(v.Pos, msg, args...)
    267 }
    268 
    269 // isGenericIntConst returns whether v is a generic integer constant.
    270 func (v *Value) isGenericIntConst() bool {
    271 	return v != nil && (v.Op == OpConst64 || v.Op == OpConst32 || v.Op == OpConst16 || v.Op == OpConst8)
    272 }
    273 
    274 // Reg returns the register assigned to v, in cmd/internal/obj/$ARCH numbering.
    275 func (v *Value) Reg() int16 {
    276 	reg := v.Block.Func.RegAlloc[v.ID]
    277 	if reg == nil {
    278 		v.Fatalf("nil register for value: %s\n%s\n", v.LongString(), v.Block.Func)
    279 	}
    280 	return reg.(*Register).objNum
    281 }
    282 
    283 // Reg0 returns the register assigned to the first output of v, in cmd/internal/obj/$ARCH numbering.
    284 func (v *Value) Reg0() int16 {
    285 	reg := v.Block.Func.RegAlloc[v.ID].(LocPair)[0]
    286 	if reg == nil {
    287 		v.Fatalf("nil first register for value: %s\n%s\n", v.LongString(), v.Block.Func)
    288 	}
    289 	return reg.(*Register).objNum
    290 }
    291 
    292 // Reg1 returns the register assigned to the second output of v, in cmd/internal/obj/$ARCH numbering.
    293 func (v *Value) Reg1() int16 {
    294 	reg := v.Block.Func.RegAlloc[v.ID].(LocPair)[1]
    295 	if reg == nil {
    296 		v.Fatalf("nil second register for value: %s\n%s\n", v.LongString(), v.Block.Func)
    297 	}
    298 	return reg.(*Register).objNum
    299 }
    300 
    301 func (v *Value) RegName() string {
    302 	reg := v.Block.Func.RegAlloc[v.ID]
    303 	if reg == nil {
    304 		v.Fatalf("nil register for value: %s\n%s\n", v.LongString(), v.Block.Func)
    305 	}
    306 	return reg.(*Register).name
    307 }
    308 
    309 // MemoryArg returns the memory argument for the Value.
    310 // The returned value, if non-nil, will be memory-typed (or a tuple with a memory-typed second part).
    311 // Otherwise, nil is returned.
    312 func (v *Value) MemoryArg() *Value {
    313 	if v.Op == OpPhi {
    314 		v.Fatalf("MemoryArg on Phi")
    315 	}
    316 	na := len(v.Args)
    317 	if na == 0 {
    318 		return nil
    319 	}
    320 	if m := v.Args[na-1]; m.Type.IsMemory() {
    321 		return m
    322 	}
    323 	return nil
    324 }
    325 
    326 // LackingPos indicates whether v is a value that is unlikely to have a correct
    327 // position assigned to it.  Ignoring such values leads to more user-friendly positions
    328 // assigned to nearby values and the blocks containing them.
    329 func (v *Value) LackingPos() bool {
    330 	// The exact definition of LackingPos is somewhat heuristically defined and may change
    331 	// in the future, for example if some of these operations are generated more carefully
    332 	// with respect to their source position.
    333 	return v.Op == OpVarDef || v.Op == OpVarKill || v.Op == OpVarLive || v.Op == OpPhi ||
    334 		(v.Op == OpFwdRef || v.Op == OpCopy) && v.Type == types.TypeMem
    335 }
    336